Suraj Bokey
01/05/2023, 3:40 PMobject
class using Mockito
. Tried the same with Mockk
it’s working.
Anyone tried doing this with Mockito
?mattinger
01/06/2023, 2:28 AMobject MyObject {
fun getValue() = 1
}
ends up being this:
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.mattinger
01/06/2023, 2:30 AM@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:
@Test
fun x() {
val mockedMyObject = Mockito.mockStatic(MyObject::class.java)
mockedMyObject.`when`<Int>(MyObject::getValue).thenReturn(4)
println(MyObject.getValue())
}
mattinger
01/06/2023, 2:34 AMSuraj Bokey
01/06/2023, 7:05 AM