2

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<>());
}
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141

1 Answers1

1

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.

Ady Junior
  • 1,040
  • 2
  • 10
  • 18
  • i did what you say and throws the following error---->java.lang.NoClassDefFoundError: org/mockito/cglib/proxy/Enhancer at org.powermock.api.extension.proxyframework.ProxyFrameworkImpl.isProxy(ProxyFrameworkImpl.java:52) at org.powermock.reflect.internal.WhiteboxImpl.getUnmockedType(WhiteboxImpl.java:1689) at org.powermock.reflect.internal.WhiteboxImpl.getType(WhiteboxImpl.java:2111) at org.powermock.reflect.internal.WhiteboxImpl.setInternalState(WhiteboxImpl.java:33 – JuanLuis Ramírez May 08 '20 at 16:43
  • The versions of libraries are conflicting, so Try this --> https://stackoverflow.com/a/36507006/2278773 – Ady Junior May 08 '20 at 18:21