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
As stated here:
Mockito.mock(Application::class.java)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With