androidunit-testingandroid-espressoandroid-fragmentscenario

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."


Solution

  • I think something like this

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