简体   繁体   中英

How to get access to a property from the test class? FragmentScenario, Espresso

I want to check my editTextView and the field of a property(crime.title). How could I get this field from the test class? That's my Test Class:

@RunWith(AndroidJUnit4::class)
class CrimeDetailFragmentTest {
    private lateinit var fragmentScenario: FragmentScenario<CrimeDetailFragment>

    @Before
    fun setUp() {
        fragmentScenario = launchFragment() }
    @After
    fun tearDown() {
        fragmentScenario.close() }
    
    @Test
    fun updatesCrimeAfterTextChange() {
        onView(withId(R.id.crime_title)).perform(replaceText("newText"))
        fragmentScenario.onFragment { fragment ->
    // Here I want to assertEquals crime.title and text from editTextView
        }
    }
}

And there is a piece of my code from Fragment Class:

class CrimeDetailFragment : Fragment() {

    private var _binding: FragmentCrimeDetailBinding? = null
    private val binding
        get() = checkNotNull(_binding) { "Cannot access binding because it is null. Is the view visible?" }

    private lateinit var crime: Crime

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        crime = Crime(
            id = UUID.randomUUID(),
            title = "",
            date = Date(),
            isSolved = false
        )

    }

That's one of the tasks in the Big Nerd Ranch Guide, 5th Edition. They recommend to use onFragment() function, but I don't know the way to do that. "For example, you could test and verify that the CheckBox and EditText are hooked up to your fragment and update the Crime. By removing the private visibility modifier on the property and using the FragmentScenario.onFragment(…) function, you can get access to a Crime and perform the appropriate assertions."

I think something like this

fragmentScenario.onFragment { fragment ->
    val textFromView = fragment.findViewById<TextView>(R.id.text_id).text
    Assert.assertEquals("expected text", textFromView)
}

I've added this dependency:
debugImplementation "androidx.test:monitor:1.6.0"
Without this dependency FragmentScenario didn't work, the test load endlessly.
And just deleted private modificator here:
private lateinit var crime: Crime
Afterwards it looks like this:

  @Test
    fun updatesCrimeAfterTextChange() {
        onView(withId(R.id.crime_title)).perform(replaceText("expected text"))
        fragmentScenario.onFragment { fragment ->
            assertEquals("expected text", fragment.crime.title)
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM