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

前端 未结 4 2071
萌比男神i
萌比男神i 2020-12-05 15:23

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

相关标签:
4条回答
  • 2020-12-05 15:47

    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"));
    }
    
    }
    
    0 讨论(0)
  • 2020-12-05 15:56

    I managed to use spy and doReturn to achieve it.

    class MyStatic {
        static String foo() { return "foo"; }
        static String foobar() { return foo() + "bar"; }
    }
    
    @Test
    public void thisShouldSpyStaticMethods() {
        // arrange
        spy(MyStatic.class);
        doReturn("mocked foo").when(MyStatic.class);
        MyStatic.foo();
    
        // act
        final String result = MyStatic.foobar();
    
        // assert
        assertThat(result).isEqualTo("mocked foobar");
    }
    

    The doReturn followed by a call to the method to be mocked looks weird (at least to me), but seems to do the trick.

    Using spy with when(MyStatic.foo()).thenReturn("mocked foo") doesn't work for me.

    PowerMockito's documentation on mocking static method.

    0 讨论(0)
  • 2020-12-05 15:57

    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

    0 讨论(0)
  • 2020-12-05 16:11

    Based on this question PowerMockito mock single static method and return object

    PowerMockito.mockStatic(MyStaticClass.class);
    

    alone does not mock all methods (in recent versions of PowerMockito at least), only enables mocking later of individual methods.

    0 讨论(0)
提交回复
热议问题