Mock static method call using @RunWith(MockitoJUnitRunner.class)

728 Views Asked by At

I'm using @RunWith(MockitoJUnitRunner.class). i need to mock a static method call, MosConfigFactory.getInstance(). I can't use @RunWith(PowerMockRunner.class). how can i mock a static method call using MockitoJUnitRunner?

1

There are 1 best solutions below

0
On

You can use mockito inline

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <version>3.8.0</version>
    <scope>test</scope>
</dependency>

Sample code :

assertEquals("foo", Foo.method());
 try (MockedStatic mocked = mockStatic(Foo.class)) {
    mocked.when(Foo::method).thenReturn("bar");
    assertEquals("bar", Foo.method());
    mocked.verify(Foo::method);
 }
 assertEquals("foo", Foo.method());

More information setup on Ofiicial Documentation

Also this is turned off by default and as per offical documentation you need to turn it on:

This mock maker is turned off by default because it is based on completely different mocking mechanism that requires more feedback from the community. It can be activated explicitly by the mockito extension mechanism, just create in the classpath a file /mockito-extensions/org.mockito.plugins.MockMaker containing the value mock-maker-inline.