I’m currently writing a unit test in Kotlin using Mockito for a function that saves data to SharedPreferences. I’m trying to verify that a method was called with specific parameters, but I’m encountering an issue when using any(Context::class.java)
and any()
.
Here’s the line of code that’s causing the problem:
verify(sharedPreferencesProvider, times(1)).saveLong(any(Context::class.java), eq(dataName), anyLong())
This line is supposed to verify that the saveLong
method of sharedPreferencesProvider
was called exactly once with a Context
object, a specific dataName
, and any Long
value.
However, the verification fails, even though I’m sure that the saveLong
method is being called with the correct parameters in the function I’m testing.
I’ve also tried using just any()
instead of any(Context::class.java)
, but that doesn’t seem to work either. It results in a NullPointerException, even though the any()
matcher should match any argument, including non-null ones.
Here’s the function I’m testing:
fun validateFrequency(data: SplashScreens, gson: Gson, viewModelScope: CoroutineScope): Boolean {
// ... (code omitted for brevity)
sharedPreferencesProvider.saveLong(context, "mp_"+ data.name, currentTime)
// ... (code omitted for brevity)
}
And here’s the test case:
@Test
fun `test validateFrequency`() = runTest(testDispatcher) {
// ... (code omitted for brevity)
val result = nudgeBottomSheetUtils.validateFrequency(data, gson, this)
assertTrue(result)
verify(sharedPreferencesProvider, times(1)).saveLong(any(Context::class.java), eq(dataName), anyLong())
// ... (code omitted for brevity)
}
Does anyone know why the verification might be failing and how I can fix it? Any help would be greatly appreciated.