Search code examples
unit-testingjunitandroid-testingrobolectric

How to get an access to a view and test if view is visible?


I got fragment and got if/else condition. Based on this condition textView visibility VISIBLE / GONE. How in robolectric test mock or get an access to that textView and check the visibility ?


Solution

  • Robolectric is used as an alternative to launch the app in the emulator, you'll want to use espresso to test what state the view is in.

    @RunWith(RobolectricTestRunner::class)
    class MyUnitTest {
    
        @Before
        fun setup() {
            // Launch activity or fragment
        }
    
        @Test
        fun 'view is visble'() {
            // when viewmodel is visible 
    
            // then, Espresso
            onView(withId(R.id.MyViewId))
                .check(matches(withEffectiveVisibility(Visibility.VISIBLE)))
        } 
    
        @Test
        fun 'view is gone'() {
            // then, Espresso
            onView(withId(R.id.MyViewId))
                .check(matches(withEffectiveVisibility(Visibility.GONE)))
        } 
    }
    

    https://android.github.io/android-test/downloads/espresso-cheat-sheet-2.1.0.pdf