0

Amateur question, but I can't seem to find an answer...

I am writing unit tests using Mockito and I have a utils function (isOnline(context)) which checks if I am offline before making a network call.

I am not trying to test that function, so I want to mock the result of that function and not run any of the code within it.

I've tried two of my usual approaches:

  • given(isOnline(context)).willReturn(true)

  • when(isOnline(application)).thenReturn(true)

But both seem to be running the isOnline method.

fun isOnline(context: Context): Boolean {
  val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
...
}

... and I am getting the error

java.lang.NullPointerException: null cannot be cast to non-null type 
 android.net.ConnectivityManager
    at org.triggerise.base.utils.NetworkUtilsKt.isOnline(NetworkUtils.kt:14)

Any suggestions on how to just mock the result without running the contents of the method?

Alon
  • 883
  • 1
  • 6
  • 18

1 Answers1

0

That's the way Java/Kotlin works - you're actually calling the method while mocking the behaviour there, so the code is executed. To work around that, you need to use doReturn (section 12. in the docs) Mockito method.

doReturn(false).when(mockedObject).isOnline(context) 

If the method is static, you have to use mockStatic method (section 48. in the docs).

try (var mockedStatic = Mockito.mockStatic(YourClass.class) {
    mockedStatic.when(() -> YourClass.isOnline(...)).thenReturn(false);

    // rest of the test 
} 
Jonasz
  • 1,617
  • 1
  • 13
  • 19
  • Thanks Jonasz! What if there is no object associated with the function? My isOnline function is a 'free standing' function part of a util. – Alon Oct 10 '22 at 07:11
  • 1
    I don't think that's possible with Mockito, unfortunately: [GitHub](https://github.com/mockito/mockito-kotlin/issues/277), [StackOverflow](https://stackoverflow.com/questions/37521384/android-kotlin-mocking-a-free-function-using-mockito-powermock). – Jonasz Oct 10 '22 at 07:51