Home > other >  Mocking Glide in Unit Test to avoid NullPointerException
Mocking Glide in Unit Test to avoid NullPointerException

Time:04-21

I'm writing unit test for a viewModel that fetches an image from the server using Glide. Code is like the following:

ViewModel.kt

class MyViewModel : ViewModel() {
    val repository = Repository()
  
    fun updateState() {
       viewModelScope.launch {
         val drawable = repository.getImage("google.com")
         withContext(Dispatchers.Main()) {
           if(drawable != null) _liveData.value = LoadedState
         }
       }
    }
}

Repository:

class Repository {

    fun getImage(url: String) {
      return Glide.with(appContext).asDrawable().load(url).submit().get()
    }
}

Test:

@Test
fun testLoadedState() {
   runBlockingTest {
      whenever(repository.getImage("")).thenReturn(mockedDrawable)
      ... rest of the test 
   }
}

Upon running the test, I get NULL POINTER EXCEPTION when glide is being executed. The error is

java.lang.NullPointerException
at com.bumptech.glide.load.engine.cache.MemorySizeCaculator.isLowMemoryDevifce(MemorySizeCalculator.java:124)

I assume I'm getting this error is because I need to mock Glide object. How can I get rid of this error and just return a mock bitmap/null image when repository.getImage() is executed in test?

CodePudding user response:

You are not actually mocking the repository you are using, since you create that repository in your viewModel.

In order to mock the repository you have to inject it into the viewmodel, then you can use your mocked one in your tests.

class MyViewModel(private val repository: Repository) : ViewModel() {

...

Then in your test you inject the mocked repository:

@Test
fun testLoadedState() {
   runBlockingTest {
   val viewModel = ViewModel(mockRepository)
    whenever(mockRepository.getImage("")).thenReturn(mockedDrawable)
      ... rest of the test 
   }
}
  • Related