Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.
like image 577
Sumit Sharma Avatar asked Dec 10 '20 15:12

Sumit Sharma


1 Answers

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
}
like image 111
nuhkoca Avatar answered Sep 20 '22 19:09

nuhkoca