Home > Software engineering >  How to get access to a property from the test class? FragmentScenario, Espresso
How to get access to a property from the test class? FragmentScenario, Espresso

Time:12-30

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

CodePudding user response:

I think something like this

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

CodePudding user response:

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)
        }
    }
  • Related