Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerMock: mocking of static methods (+ return original values in some particular methods)

I use PowerMock 1.4.7 and JUnit 4.8.2

I need to mock only some static methods and I want others (from the same class) just to return original value. When I mock with mockStatic and don't call when().doReturn() all static methods return their defaults - like null when returning Object or false when returning boolean...etc. So I try to use thenCallRealMethod explicitly on each static method to return default implementation (means no mocking/ no fakes) but I don't know how to call it on every possible arguments variations (= I want for every possible input call original method). I only know how to mock concrete argument variation.

like image 210
Michal Bernhard Avatar asked Feb 01 '11 08:02

Michal Bernhard


People also ask

Can static methods be mocked?

Since static method belongs to the class, there is no way in Mockito to mock static methods.

Can static methods be mocked C#?

You can use Moq to mock non-static methods but it cannot be used to mock static methods. Although static methods cannot be mocked easily, there are a few ways to mock static methods. You can take advantage of the Moles or Fakes framework from Microsoft to mock static method calls.

How do you mock a private static method?

For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.


2 Answers

You can use a spy on your static class and mock only specific methods:

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyStaticTest.MyStaticClass.class)
public class MyStaticTest {

public static class MyStaticClass {
    public static String getA(String a) {
        return a;
    }
    public static String getB(String b) {
        return b;
    }
}

@Test
public void should_partial_mock_static_class() throws Exception {
    //given
    PowerMockito.spy(MyStaticClass.class);
    given(MyStaticClass.getB(Mockito.anyString())).willReturn("B");
    //then
    assertEquals("A", MyStaticClass.getA("A"));
    assertEquals("B", MyStaticClass.getA("B"));
    assertEquals("C", MyStaticClass.getA("C"));
    assertEquals("B", MyStaticClass.getB("A"));
    assertEquals("B", MyStaticClass.getB("B"));
    assertEquals("B", MyStaticClass.getB("C"));
}

}
like image 51
denis.solonenko Avatar answered Sep 18 '22 03:09

denis.solonenko


You can also use the stubbing API:

stub(method(MyStaticClass.class, "getB")).toReturn("B");

Edit:

To use stub and method statically import methods from these packages:

  1. org.powermock.api.support.membermodification.MemberModifier
  2. org.powermock.api.support.membermodification.MemberMatcher

For more info refer to the documentation

like image 22
Johan Avatar answered Sep 20 '22 03:09

Johan