Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

android - Mock object in activity with espresso UI test

I want to mock an object which exists in activity the object has a function which return boolean value when activity launch, this boolean value determines TextView visibility, it will be visible if the function returns true and gone if returns false. but when I apply when(...).thenReturn(...) on this mock object and launch activity from test it returns a real value from shared preferences, not the value I which in thenReturn(..) so the test fails!.

Here is my activity:

class MyActivity : AppCompatActivity(), HasAndroidInjector {

    @Inject
    lateinit var manager: TestManager
    @Inject
    lateinit var androidInjector: DispatchingAndroidInjector<Any>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my)

        AndroidInjection.inject(this)
        setViewVisibility()
    }

    private fun setViewVisibility() {
        if(manager.isEntryPointsEnabled)
            test_tv.visibility = View.VISIBLE
        else
            test_tv.visibility = View.GONE
    }

    override fun androidInjector(): AndroidInjector<Any> {
        return androidInjector
    }
}

Here is my test file:

@RunWith(AndroidJUnit4::class)
class ABFeaturesUITesting {

    @Rule
    @JvmField
    var activityRule = ActivityTestRule<MyActivity>(MyActivity::class.java, true, false)  // Activity is not launched immediately

    @Mock
    lateinit var testManager: TestManager

    @Before
    fun setUp() {
        MockitoAnnotations.initMocks(this)
    }
    @Test
    fun testNewUI_Visibility() {

        Mockito.`when`(testManager.isEntryPointsEnabled).thenReturn(false)
        activityRule.launchActivity(Intent())
        onView(withId(R.id.test_tv)).check(matches(not(isDisplayed())))
    }

}

Here is class that the activity depends on:

public class TestManager {

    private ABFeatures abFeatures;

    @Inject
    public TestManager(SharedPreferencesUtils sharedPreferencesUtils) {
        abFeatures = sharedPreferencesUtils.getEnableFeatures();
    }

    public boolean isEntryPointsEnabled() {
        return abFeatures != null && abFeatures.isEntry_points();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...