question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Mock ViewModel in Activity for UI Testing with Espresso

See original GitHub issue

I’m try to setup UI testing similar GithubBrowserSample and look like sample project have only mock ViewModel for Fragment but for Activity it doesn’t.

So, on my code activityRule.activity.viewModelFactory = createViewModelFor(viewModel) it doesn’t set before onCreate() in Activity, meant it doesn’t use mock ViewModel.

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 about this issue please?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:15
  • Comments:14

github_iconTop GitHub Comments

10reactions
kekefigurecommented, Mar 29, 2018

Use the following class to create the activity instance: https://developer.android.com/reference/android/support/test/runner/intercepting/SingleActivityFactory.html Then you can create different factories for mocked/injected activities. Example with dagger2 injection:

private SingleActivityFactory<MainActivity> injectedFactory = new SingleActivityFactory<MainActivity>(MainActivity.class) {
        @Override
        protected MainActivity create(Intent intent) {
            MainActivity activity = new MainActivity();
            activity.viewModelFactory = testApp.daggerTestAppComponent.vmFactory();
            return activity;
        }
 };

@Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(injectedFactory, false, false);
0reactions
aumarbellocommented, Mar 31, 2019

@danielwilson1702 Can you please post your final working code? I’m currently trying to mock an activity’s viewmodel and haven’t been able to achieve it.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to correctly mock ViewModel on androidTest
Recommendations: 1) Mock the data sources the view model is constructed from or 2) add a fragment.setViewModel() and Mark it as only for...
Read more >
Android UI Test: Mocking the ViewModel with or without ...
The projects uses Espresso for UI testing. Since each fragment is limited to a ViewModel, each test mocks related ViewModel to run the...
Read more >
Mocking ViewModel for Espresso tests : r/androiddev - Reddit
My idea is to mock (using Mockk) the ViewModel to be able to control the flows ... At this point why do you...
Read more >
Testing ViewModels and Activities in Your MVVM App - Medium
In the setUp() function, we first invoke onCreate() of the activity (via activityController.create() ). Then we swap out the real view model ......
Read more >
Testing the untestable — the case of the ViewModel delegate
You could argue that you should not try to unit test Activities or Fragment as those are components where proper UI testing should...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found