Unable to mock the methods from `object` class using `Mockito`. Tried the same with `Mockk` it’s wor...
s
Unable to mock the methods from
object
class using
Mockito
. Tried the same with
Mockk
it’s working. Anyone tried doing this with
Mockito
?
m
Basically the methods from an object are calling into static code. When you create an object in kotlin, it’s the same as creating the singleton pattern on your own:
Copy code
object MyObject {
    fun getValue() = 1
}
ends up being this:
Copy code
public final class MyObject {
   @NotNull
   public static final MyObject INSTANCE;

   public final int getValue() {
      return 1;
   }

   private MyObject() {
   }

   static {
      MyObject var0 = new MyObject();
      INSTANCE = var0;
   }
}
So when you say
MyObject.getValue()
you are actually accessing the static
INSTANCE
field before calling the
getValue()
function.
Mockito isn’t super great at mocking static stuff like that. The best i’ve found is to annotate the methods in the object with
@JvmStatic
and then you can use the built in static mocking support, which comes with it’s own limitations mind you, and you have to make sure you’re running your test in a single thread from what i understand:
Copy code
@Test
fun x() {
    val mockedMyObject = Mockito.mockStatic(MyObject::class.java)
    mockedMyObject.`when`<Int>(MyObject::getValue).thenReturn(4)
    println(MyObject.getValue())
}
This is mostly because the mockStatic support in mockito is java based, and not optimized for kotlin. Mockk is designed from the ground up for pure kotlin code, and thus doesn’t come with some of the baggage that mockito does. What i’d say is there’s no reason the two can’t coexist in the same project. If mockk is needed for one test just for this reason, then use it.
s
Thanks @mattinger
1549 Views