Testing with FragmentScenario (Chapter 9)

Hello, I’m having some trouble understanding how to check the checkbox’s state with the crime solved state from the CrimeDetailFragment. The book mentioned accessing the crime through .onFragment although I haven’t found how to match it using the Espresso API.

My intuition was first to try something like this:

class CrimeDetailFragmentTest {

    private lateinit var scenario: FragmentScenario<CrimeDetailFragment>

    @Before
    fun setUp() {
        scenario = launchFragmentInContainer()
    }

    @After
    fun tearDown() {
        scenario.close()
    }

    @Test
    fun checkBoxStateEqualsCrimeSolvedState() {
        scenario.onFragment {
            fragment ->
            // how to check checkbox value against crime's solved Status?
            onView(withId(R.id.crime_solved_checkbox)).check(matches(fragment.crime.solvedStatus))
        }
            
    }
}

A hint would be very much appreciated.

1 Like

You were close, but you need to use isChecked() or isNotChecked() instead of fragment.crime.solvedStatus when making an assertion on that checkbox.

Look at ViewMatchers  |  Android Developers to find more ways you can make assertions on Views if you want.

Thanks for the reply, I’m still confused about this challenge.
Using isChecked() would tell me if the checkbox is checked or not, but the point of the challenge was to see if the checkbox and text input modify the Crime object as far as I understood. So can you even check that using Espresso API?

image

What “appropriate assertions” can we perform to check if the Crime is updated with Espresso?

Ahhhhhh, I get what you are asking now. Asserting on data and asserting on views require slightly different APIs. In order to assert on data, you use the plain old assertEquals() or assertTrue() or any of the other basic JUnit assertions. In order to assert on view, you use the Espresso APIs.

So in this situation, inside the scenario.onFragment {...} lambda expression, you would make an assertion on fragment.crime.solvedStatus, while outside the lambda expression you would make an assertion on onView(withId(R.id.crime_solved_checkbox)).

I hope this helps out.

1 Like