Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mockito.mockStatic not working with Kotlin but it works in Java #459

Open
aakash1313 opened this issue May 31, 2022 · 1 comment
Open

Mockito.mockStatic not working with Kotlin but it works in Java #459

aakash1313 opened this issue May 31, 2022 · 1 comment

Comments

@aakash1313
Copy link

I was trying a mock a static method inside my Kotlin class for a unit test, but it seems the Java version of my Unit Test is successful but the Kotlin version is failing

@RunWith(RobolectricTestRunner.class)
public class MyTest {

    @Test
    public void givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() {
        RestAdapterFactory restAdapterFactoryMock = Mockito.mock(RestAdapterFactory.class);
        try (MockedStatic<RestAdapterFactory> utilities = Mockito.mockStatic(RestAdapterFactory.class)) {
            utilities.when(() -> RestAdapterFactory.getInstance(Mockito.any()))
                    .thenReturn(restAdapterFactoryMock);

            assertEquals(restAdapterFactoryMock, RestAdapterFactory.getInstance("fd"));
        }
    }
}

This test is running successfully but the Kotlin version of it below is failing

Kotlin Version

@Test
fun givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() {
val restAdapterFactoryMock = Mockito.mock(RestAdapterFactory::class.java)
Mockito.mockStatic(RestAdapterFactory::class.java).use { utilities ->
utilities.`when`<Any> { getInstance(Mockito.any()) }.thenReturn(restAdapterFactoryMock)
Assert.assertEquals(restAdapterFactoryMock, getInstance("test"))
  }
} 

Getting the below exception:

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(any());
    verify(mock).someMethod(contains("foo"))

Can someone help with this ?

@navinpd
Copy link

navinpd commented Jun 9, 2022

Basically when we write code in kotlin the java bytecode conversion creates multiple layer of static, final classes & functions. This makes the mocking difficult on multiple layers of static / final functions. Easy for investigation is to look for decompiled bytecode.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants