简体   繁体   中英

Mocking Glide in Unit Test to avoid NullPointerException

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?

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 
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM