Android Architecture ViewModel component - How to trick ViewModel into test activity?

I'm trying to set up user interface testing similar to GithubBrowserSample , and it looks like the sample project has only a mock ViewModel for Fragment , but not an example for Activity .

Here is my code where I am trying to test the Activity by mocking the ViewModel . But ViewModel not set before onCreate() in Activity.

 @RunWith(AndroidJUnit4::class) class MainActivityTest { val viewModel = mock(MainViewModel::class.java) @Rule @JvmField val activityRule = ActivityTestRule<MainActivity>(MainActivity::class.java, true, true) private val liveData = MutableLiveData<Resource<Object>>() @Before open fun setUp() { activityRule.activity.viewModelFactory = createViewModelFor(viewModel) `when`(viewModel.liveData).thenReturn(liveData) viewModel.liveData?.observeForever(mock(Observer::class.java) as Observer<Resource<Object>>) liveData.postValue(Resource.success(Object())) } fun <T : ViewModel> createViewModelFor(model: T): ViewModelProvider.Factory = object : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(model.javaClass)) { return model as T } throw IllegalArgumentException("unexpected model class " + modelClass) } } } 

Can someone help me on this?

+5
source share
1 answer

JUnit @Rule do their customization before the @Before methods, so your activity starts and the life cycle begins before you call the setUp() method. To avoid this, pass false as the third parameter to the rule constructor. This suggests that it does not start this operation automatically, so you can do your setup in advance.

Then you need to run the action manually before running the tests. You can create an intent like val intent = Intent(InstrumentationRegistry.targetContext, MainActivity::class.java) and then pass it to activityRule.launchActivity(intent) .

0
source

Source: https://habr.com/ru/post/1274339/


All Articles