I am trying to write unit test for my ViewModel class.
In this case, I have an activity that when created, it subscribes to my repo (LiveData from viewModel) and retrieves a list of Github repositories from network or database.
What should I be testing here? I tried to write two test methods:
dontFetchWithoutObservers which fails with the following:
[![enter image description here][1]][1]
fetchWhenObserved which fails with the following:
[![enter image description here][2]][2]
Here's my ViewModel class:
class MainViewModel #ViewModelInject constructor(mainRepository: MainRepository) : ViewModel() {
val repo: LiveData<Resource<List<Repository>>> = mainRepository.getRepositories()
}
And my ViewModel test class:
#RunWith(JUnit4::class)
class MainViewModelTest {
#Rule
#JvmField
val instantTaskExecutorRule = InstantTaskExecutorRule()
private val mainRepository = mock(MainRepository::class.java)
private lateinit var mainViewModel: MainViewModel
#Before
fun init() {
mainViewModel = MainViewModel(mainRepository)
}
#Test
fun dontFetchWithoutObservers() {
verify(mainRepository, never()).getRepositories()
}
#Test
fun fetchWhenObserved() {
mainViewModel.repo.observeForever(mock())
verify(mainRepository).getRepositories()
}
}
you are not mocking the getRepositories method and in fact the error you get is: NPE.
Provide a mock for getRepositories method.
`when`(mainRepository.getRepositories()).thenReturn(YourObject)
Also I would go and check the contents of getRepositories instead of just verifying that it is being invoked.
Related
And then I'm seeing
[Test worker #coroutine#1] test
[Test worker #coroutine#2] viewModel
So this is giving me problems at the time to verify because it says that there's empty.
I'm using in my viewModel a CoroutineDispatcher injected with Hilt as
#HiltViewModel
class LocationsViewModel #Inject constructor(
private val locationsUseCase: LocationsUseCase,
#IODispatcher private val dispatcher: CoroutineDispatcher) : ViewModel() {
init { viewModelScope.launch(dispatcher) { locationsUseCase() }}
}
And the test I'm doing
private val testDispatcher = StandardTestDispatcher()
#Test
fun test() = runTest(testDispatcher){ ... }
fun createLocationsViewModel() = LocationsViewModel(locationsUseCase, testDispatcher)
Your viewmodel tries to initialise, but fails, because it doesn't know what to do with locationsUseCase call. Try mock it in setUp() method. With mockito-kotlin and mockito-core dependencies it would be something like
#Before
fun setUp() = runTest(testDispatcher) {
whenever(locationsUseCase.invoke()).thenReturn(Result.Success)
}
This code is not strict, because I don't know the rest of your code base. So think of it as a reference.
I am using Hilt for DI in my project. I am trying write unit test cases for LiveData object, but it's not coming under coverage.
ViewModel
#HiltViewModel
class HealthDiagnosticsViewModel #Inject constructor(
private var networkHelper: NetworkHelper
) : ViewModel() {
var result = MutableLiveData<Int>()
.....
}
My unit test class is as below:
HealthViewModelTest
#HiltAndroidTest
#RunWith(RobolectricTestRunner::class)
#Config(application = HiltTestApplication::class)
class HealthDiagnosticsViewModelTest{
#get:Rule
var hiltRule = HiltAndroidRule(this)
#Inject
lateinit var networkHelper: NetworkHelper
lateinit var healthDiagnosticsViewModel: HealthDiagnosticsViewModel
#Before
fun setUp() {
hiltRule.inject()
healthDiagnosticsViewModel = HealthDiagnosticsViewModel(networkHelper)
}
#Test
fun testGetResult() {
val result = healthDiagnosticsViewModel.result.value
Assert.assertEquals(null, result)
}
#Test
fun testSetResult() {
healthDiagnosticsViewModel.result.value = 1
Assert.assertEquals(1, healthDiagnosticsViewModel.result.value)
}
}
Test Cases are passed but it's not coming under method coverage.
I'll share with you the an example of my code that would solve your problem.
I'm usnig ViewModel with Dagger Hilt
You don't have to use Robelectric, you can use MockK library.
Replace your HiltRule with this Rule:
#get:Rule
var rule: TestRule = InstantTaskExecutorRule()
This is my ViewModel class
using MockK, you can mock the networkHelper class without Hilt.
So, your setup method will be like that:
lateinit var networkHelper: NetworkHelper
......
......
......
#Before
fun setUp() {
networkHelper = mockk<NetworkHelper>()
healthDiagnosticsViewModel = HealthDiagnosticsViewModel(networkHelper)
}
4)The most important part in your test is to Observe to the LiveData first.
#Test
fun testGetResult() {
healthDiagnosticsViewModel.result.observeForever {}
val result = healthDiagnosticsViewModel.result.value
Assert.assertEquals(null, result)
}
You can observe to the livedata for each unit test, but keep in mind to Observe first before change data.
So I want to test my jetpack compose project. It's easy enough running an instrument test following [these instructions]1 on android dev site, but when you add #HiltViewModel injection into the combination things get complicated.
I'm trying to test a pretty simple compose screen with a ViewModel that has an #Inject constructor.
The screen itself looks like this:
#Composable
fun LandingScreen() {
val loginViewModel: LoginViewModel = viewModel()
MyTheme {
Surface(color = MaterialTheme.colors.background) {
val user by loginViewModel.user.observeAsState()
if (user != null) {
MainScreen()
} else {
LoginScreen(loginViewModel)
}
}
}
}
and this is the view model:
#HiltViewModel
class LoginViewModel #Inject constructor(private val userService: UserService) : ViewModel() {
val user = userService.loggedInUser.asLiveData()
}
User service is of course backed by a room database and the loggedInUser property returns a Flow.
Things work as expected on standard run but when trying to run it in an instrument test it can't inject the view model.
#HiltAndroidTest
class LandingScreenTest {
#get:Rule
var hiltRule = HiltAndroidRule(this)
#get:Rule
val composeTestRule = createComposeRule()
#Inject
lateinit var loginViewModel: LoginViewModel
#Before
fun init() {
hiltRule.inject()
}
#Test
fun MyTest() {
composeTestRule.setContent {
MyTheme {
LandingScreen()
}
}
composeTestRule.onNodeWithText("Welcome").assertIsDisplayed()
}
}
Injection of an #HiltViewModel class is prohibited since it does not
create a ViewModel instance correctly. Access the ViewModel via the
Android APIs (e.g. ViewModelProvider) instead. Injected ViewModel:
com.example.viewmodels.LoginViewModel
How do you make that work with the ViewModelProvider instead of the #HiltViewModel?
Hilt needs an entry point to inject fields. In this case that would probably be an Activity annotated with #AndroidEntryPoint. You can use your MainActivity for that, but that would mean that you would then have to add code to every test to navigate to the desired screen which could be tedious depending on the size of your app, and is not feasible if your project is multimodule and your current Test file does not have access to MainActivity. Instead, you could create a separate dummy Activity whose sole purpose is to host your composable (in this case LoginScreen) and annotate it with #AndroidEntryPoint. Make sure to put it into a debug directory so it's not shipped with the project. Then you can use createAndroidComposeRule<Activity>() to reference that composable. You dont need to inject the ViewModel directly so get rid of that line too.
In the end your Test File should look like this:
#HiltAndroidTest
class LandingScreenTest {
#get:Rule(order = 0)
val hiltRule = HiltAndroidRule(this)
#get:Rule(order = 1)
val composeRule = createAndroidComposeRule<LoginTestActivity>()
#Before
fun init() {
hiltRule.inject()
}
#Test
fun MyTest() {
composeTestRule.onNodeWithText("Welcome").assertIsDisplayed()
}
}
And your your dummy activity can look like this:
#AndroidEntryPoint
class LoginTestActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
LoginScreen()
}
}
}
And the debug directory would look like this:debug directory with dummy activity
Yes the debug directory has its own manifest and that is where you should add the dummy activity. set exported to false.
Try to do something like this:
#HiltAndroidTest
class LandingScreenTest {
#get:Rule
var hiltRule = HiltAndroidRule(this)
#get:Rule
val composeTestRule = createComposeRule()
// Remove this line #Inject
lateinit var loginViewModel: LoginViewModel
#Before
fun init() {
hiltRule.inject()
}
#Test
fun MyTest() {
composeTestRule.setContent {
loginViewModel= hiltViewModel() // Add this line
MyTheme {
LandingScreen()
}
}
composeTestRule.onNodeWithText("Welcome").assertIsDisplayed()
}
}
You must annotate any UI test that uses Hilt with #HiltAndroidTest. This annotation is responsible for generating the Hilt components for each test.
https://developer.android.com/training/dependency-injection/hilt-testing
I have a viewmodel that only emits the value of repo when I subscribe to it in the activity. I am trying to unit test the viewmodel (see code below) but I am getting NPE because repo is null. How can I unit test it? Is it possible?
class MainViewModel #ViewModelInject constructor(mainRepository: MainRepository) : ViewModel() {
val repo: LiveData<Resource<List<Repository>>> = mainRepository.getRepositories()
}
#RunWith(JUnit4::class)
class MainViewModelTest {
#Rule
#JvmField
val instantTaskExecutorRule = InstantTaskExecutorRule()
private val mainRepository = mock(MainRepository::class.java)
private lateinit var mainViewModel: MainViewModel
#Before
fun init() {
mainViewModel = MainViewModel(mainRepository)
}
#Test
fun testGetRepos() {
mainViewModel.repo.observeForever(mock()) /* NPE at this point as repo is null*/
verify(mainRepository).getRepositories()
}
}
Create an interface something like IMainRepository have your actual repository class implement it
class MainRepository : IMainRepository
Then change your ViewModel constructor to accept the interface
class MainViewModel #ViewModelInject constructor(mainRepository: IMainRepository) : ViewModel()
Then create a Mock class that implements the interface and what it is suppose to do
class MockMainRepository : IMainRepository
in your test create a new instance of the mock class and pass that to your ViewModel to test
private val mockMainRepository = MockMainRepository()
#Before
fun init() {
mainViewModel = MainViewModel(mainRepository)
}
I'm currently writing some UI unit tests for a fragment, and one of these #Test is to see if a list of objects is correctly displayed, this is not an integration test, therefore I wish to mock the ViewModel.
The fragment's vars:
class FavoritesFragment : Fragment() {
private lateinit var adapter: FavoritesAdapter
private lateinit var viewModel: FavoritesViewModel
#Inject lateinit var viewModelFactory: FavoritesViewModelFactory
(...)
Here's the code:
#MediumTest
#RunWith(AndroidJUnit4::class)
class FavoritesFragmentTest {
#Rule #JvmField val activityRule = ActivityTestRule(TestFragmentActivity::class.java, true, true)
#Rule #JvmField val instantTaskExecutorRule = InstantTaskExecutorRule()
private val results = MutableLiveData<Resource<List<FavoriteView>>>()
private val viewModel = mock(FavoritesViewModel::class.java)
private lateinit var favoritesFragment: FavoritesFragment
#Before
fun setup() {
favoritesFragment = FavoritesFragment.newInstance()
activityRule.activity.addFragment(favoritesFragment)
`when`(viewModel.getFavourites()).thenReturn(results)
}
(...)
// This is the initial part of the test where I intend to push to the view
#Test
fun whenDataComesInItIsCorrectlyDisplayedOnTheList() {
val resultsList = TestFactoryFavoriteView.generateFavoriteViewList()
results.postValue(Resource.success(resultsList))
(...)
}
I was able to mock the ViewModel but of course, that's not the same ViewModel created inside the Fragment.
So my question really, has someone done this successfully or has some pointers/references that might help me out?
Also, I've tried looking into the google-samples but with no luck.
For reference, the project can be found here: https://github.com/JoaquimLey/transport-eta/
Within your test setup you'll need to provide a test version of the FavoritesViewModelFactory which is being injected in the Fragment.
You could do something like the following, where the Module will need to be added to your TestAppComponent:
#Module
object TestFavoritesViewModelModule {
val viewModelFactory: FavoritesViewModelFactory = mock()
#JvmStatic
#Provides
fun provideFavoritesViewModelFactory(): FavoritesViewModelFactory {
return viewModelFactory
}
}
You'd then be able to provide your Mock viewModel in the test.
fun setupViewModelFactory() {
whenever(TestFavoritesViewModelModule.viewModelFactory.create(FavoritesViewModel::class.java)).thenReturn(viewModel)
}
I have solved this problem using an extra object injected by Dagger, you can find the full example here: https://github.com/fabioCollini/ArchitectureComponentsDemo
In the fragment I am not using directly the ViewModelFactory, I have defined a custom factory defined as a Dagger singleton:
https://github.com/fabioCollini/ArchitectureComponentsDemo/blob/master/uisearch/src/main/java/it/codingjam/github/ui/search/SearchFragment.kt
Then in the test I replace using DaggerMock this custom factory using a factory that always returns a mock instead of the real viewModel:
https://github.com/fabioCollini/ArchitectureComponentsDemo/blob/master/uisearchTest/src/androidTest/java/it/codingjam/github/ui/repo/SearchFragmentTest.kt
Look like, you use kotlin and koin(1.0-beta).
It is my decision for mocking
#RunWith(AndroidJUnit4::class)
class DashboardFragmentTest : KoinTest {
#Rule
#JvmField
val activityRule = ActivityTestRule(SingleFragmentActivity::class.java, true, true)
#Rule
#JvmField
val executorRule = TaskExecutorWithIdlingResourceRule()
#Rule
#JvmField
val countingAppExecutors = CountingAppExecutorsRule()
private val testFragment = DashboardFragment()
private lateinit var dashboardViewModel: DashboardViewModel
private lateinit var router: Router
private val devicesSuccess = MutableLiveData<List<Device>>()
private val devicesFailure = MutableLiveData<String>()
#Before
fun setUp() {
dashboardViewModel = Mockito.mock(DashboardViewModel::class.java)
Mockito.`when`(dashboardViewModel.devicesSuccess).thenReturn(devicesSuccess)
Mockito.`when`(dashboardViewModel.devicesFailure).thenReturn(devicesFailure)
Mockito.`when`(dashboardViewModel.getDevices()).thenAnswer { _ -> Any() }
router = Mockito.mock(Router::class.java)
Mockito.`when`(router.loginActivity(activityRule.activity)).thenAnswer { _ -> Any() }
StandAloneContext.loadKoinModules(hsApp + hsViewModel + api + listOf(module {
single(override = true) { router }
factory(override = true) { dashboardViewModel } bind ViewModel::class
}))
activityRule.activity.setFragment(testFragment)
EspressoTestUtil.disableProgressBarAnimations(activityRule)
}
#After
fun tearDown() {
activityRule.finishActivity()
StandAloneContext.closeKoin()
}
#Test
fun devicesSuccess(){
val list = listOf(Device(deviceName = "name1Item"), Device(deviceName = "name2"), Device(deviceName = "name3"))
devicesSuccess.postValue(list)
onView(withId(R.id.rv_devices)).check(ViewAssertions.matches(ViewMatchers.isCompletelyDisplayed()))
onView(withId(R.id.rv_devices)).check(matches(hasDescendant(withText("name1Item"))))
onView(withId(R.id.rv_devices)).check(matches(hasDescendant(withText("name2"))))
onView(withId(R.id.rv_devices)).check(matches(hasDescendant(withText("name3"))))
}
#Test
fun devicesFailure(){
devicesFailure.postValue("error")
onView(withId(R.id.rv_devices)).check(ViewAssertions.matches(ViewMatchers.isCompletelyDisplayed()))
Mockito.verify(router, times(1)).loginActivity(testFragment.activity!!)
}
#Test
fun devicesCall() {
onView(withId(R.id.rv_devices)).check(ViewAssertions.matches(ViewMatchers.isCompletelyDisplayed()))
Mockito.verify(dashboardViewModel, Mockito.times(1)).getDevices()
}
}
In the example you provided, you are using mockito to return a mock for a specific instance of your view model, and not for every instance.
In order to make this work, you will have to have your fragment use the exact view model mock that you have created.
Most likely this would come from a store or a repository, so you could put your mock there? It really depends on how you setup the acquisition of the view model in your Fragments logic.
Recommendations:
1) Mock the data sources the view model is constructed from or
2) add a fragment.setViewModel() and Mark it as only for use in tests. This is a little ugly, but if you don't want to mock data sources, it is pretty easy this way.
One could easily mock a ViewModel and other objects without Dagger simply by:
Create a wrapper class that can re-route calls to the ViewModelProvider. Below is the production version of the wrapper class that simply passes the calls to the real ViewModelProvider which is passed in as a parameter.
class VMProviderInterceptorImpl : VMProviderInterceptor { override fun get(viewModelProvider: ViewModelProvider, x: Class<out ViewModel>): ViewModel {
return viewModelProvider.get(x)
}
}
Adding getters and setters for this wrapper object to the Application class.
In the Activity rule, before an activity is launched, swap out the real wrapper with a mocked wrapper that does not route the get ViewModel call to the real viewModelProvider and instead provides a mocked object.
I realize this is not as powerful as dagger but the simplicity is attractive.