Null pointer exception when stubbing

  android, kotlin, mockito

Good afternoon, I have a nullpointer exception when stubbing

package com.micheladrien.android.fresquerappel

import android.app.Application
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.micheladrien.fresquerappel.R
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock    
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.mockito.junit.MockitoJUnitRunner


@RunWith(MockitoJUnitRunner::class)
class MainViewModelTest {

  @Rule
  @JvmField
  var instantTaskExecutorRule = InstantTaskExecutorRule()    

  @Mock
  val applicationMock: Application = mock(Application::class.java)
 
  @Before
  fun setUpTaskDetailViewModel() {
        `when`(applicationMock.getString(R.string.collage_climat)).thenReturn("Climat")
    }
    }

I need to stub this function because my viewmodel gets strings from context.

According to this blog post : https://codepills.com/2018/05/10/3-basic-mistakes-for-nullpointerexception-when-mock/
I should replace when thenreturn by when then (answer) which if it’s true, why ?

I have already Tested : Changing R.id value to a brut number. => Same error
Mocking the file inside the before and using lateinit for the declaration at @Mock => same error

Unlike previous question thread Mockito – NullpointerException when stubbing Method
I am directly stubbing the method. Not stubbing the method of the object of another method.

Any help would be greatly appreciated.

Source: Android Questions

LEAVE A COMMENT