14

How to use Mockito.mockStatic for mocking static methods in kotlin android ?

This is my code:

    class MyUtilClassTest {
       @Test
       fun testIsEnabled() {
          Mockito.mockStatic(MyUtilClass::class.java, Mockito.CALLS_REAL_METHODS)
                .use { mocked ->
                    mocked.`when`<Boolean> { MyUtilClass.isEnabled() }.thenReturn(true)
                    assertTrue(MyUtilClass.isEnabled())
                }
       }
    }
    
    object MyUtilClass {
       fun isEnabled(): Boolean = false
    }

I am getting this exception:

org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:

  1. you stub either of: final/private/equals()/hashCode() methods. Those methods cannot be stubbed/verified. Mocking methods declared on non-public parent classes is not supported.
  2. inside when() you don't call method on mock but on some other object.
Sumit Sharma
  • 231
  • 2
  • 8
  • If your objective is to mock Kotlin objects, there's already an answer for that: https://stackoverflow.com/questions/37977320/how-to-mock-a-kotlin-singleton-object – Muhammad Faiq Mar 29 '21 at 10:35

2 Answers2

6

If you annotate your function isEnabled with @JvmStatic, you won't get any error. As @Neige pointed out, static functions in Kotlin are actually not static in bytecode by default. Therefore, we need to mark our function with @JvmStatic in order to generate additional static getter/setter methods.

object MyUtilClass {
   @JvmStatic
   fun isEnabled(): Boolean = false
}
nuhkoca
  • 1,777
  • 4
  • 20
  • 44
2

From the JVM point of view MyUtilClass.isEnabled() is not a static class/function. You can use Show Kotlin Bytecode to understand what is behind

public final class MyUtilClass {
   public static final MyUtilClass INSTANCE;

   public final boolean isEnabled() {
      return false;
   }

   private MyUtilClass() {
   }

   static {
      MyUtilClass var0 = new MyUtilClass();
      INSTANCE = var0;
   }
}
Neige
  • 2,770
  • 2
  • 15
  • 21