How to Mock a static method with mockito?

Viewed 18426

I need to mock a static method with moockito but I could not this is my code

this is the class i want to mock
String buc = TrackerGenerator.getMetadataLocalThread().getIdUsuarioFinal();

and this is the test

 @Test
   public void serviceTest() {
   TrackerGenerator trackerGenerator = mock(TrackerGenerator.class);
 when(TrackerGenerator.getMetadataLocalThread().getIdUsuarioFinal()).thenReturn("0");
      TrackerGenerator.setMetadataLocalThread(new ThreadLocal<>());
}
1 Answers

Since static method belongs to the class, there is no way in Mockito to mock static methods. However, you can use PowerMock along with Mockito framework to mock static methods.

A simple class with a static method:

public class Utils {

    public static boolean print(String msg) {
        System.out.println(msg);

        return true;
    }
}

Class test mocking static method using Mockito and PowerMock in JUnit test case:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Utils.class)
public class JUnit4PowerMockitoStaticTest{

    @Test
    public void test_static_mock_methods() {
        PowerMockito.mockStatic(Utils.class);
        when(Utils.print("Hello")).thenReturn(true);
        when(Utils.print("Wrong Message")).thenReturn(false);

        assertTrue(Utils.print("Hello"));
        assertFalse(Utils.print("Wrong Message"));

        PowerMockito.verifyStatic(Utils.class, atLeast(2));
        Utils.print(anyString());
    }
}

For more details see this link.

Related