Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test a ViewModel that extends AndroidViewModel. Having issues with the application in the constructor

So I'm having to write unit tests and I need to test my ViewModels.

I have a base ViewModel and that BaseViewModel extends AndroidViewModel. The reason I extend AndroidViewModel is so that I can use the context for Dagger.

My BaseViewModel.

public class BaseViewModel extends AndroidViewModel {

protected @Inject SharedPreferencesHelper sharedPreferencesHelper;

public BaseViewModel(@NonNull Application application) {
    super(application);

    //Only inject sharedPreferences since it is used in almost all of the VMs.
    ((CommissioningApplication) getApplication()).getAppComponent().inject(this);
}

}

Essentially I'm having issues creating an instance of my ViewModel in my unit tests. I have tried many things and have been unsuccessful.

I have considered extending ViewModel instead of AndroidViewModel and creating a Factory that will pass the application context to my ViewModels. But in the end I will run towards the same issue whenever I try to create an instance of my ViewModel.

Does anyone have an example that I could follow on how to test this? Or would have I have to do Instrumented testing instead of Unit testing?

I'm very new to testing so maybe I'm not doing things properly, any help would be great.

Thanks

like image 262
huey77 Avatar asked Nov 08 '22 04:11

huey77


1 Answers

As stated here:

Mockito.mock(Application::class.java)
like image 110
Refael Sheinker Avatar answered Nov 14 '22 17:11

Refael Sheinker