How can I test two static methods (one invokes the other) with PowerMockito?

守給你的承諾、 提交于 2019-12-25 07:13:58

问题


How can I test the first static method method(String str, Param param)?

public class Example {

    public static Example method(String str, Param param) {
        return method(str, param, null);
    }

    private static Example method(String str, Param param, SomeClass obj) {
        // ...
    }
}

I try to test it with code below

@Test
public void should_invoke_overloaded_method() throws Exception {

    final String str  = "someString";    
    mockStatic(Example.class);

    when(Example.method(str, paramMock))
            .thenCallRealMethod();

    when(Example.method(str, paramMock, null))
            .thenReturn(expectedMock);

    Example.method(str, paramMock);
    verifyStatic();
}

But with no luck. How can I fix for example this test to verify invocation of the second method?


回答1:


This code works:

import static org.junit.Assert.assertSame;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Example.class)
public class ExampleTest {
    @Test
    public void should_invoke_overloaded_method() throws Exception {
        final String str = "someString";
        Param paramMock = mock(Param.class);
        Example expectedMock = mock(Example.class);

        mockStatic(Example.class);

        when(Example.method(str, paramMock)).thenCallRealMethod();
        when(Example.class, "method", str, paramMock, null).thenReturn(expectedMock);

        assertSame(expectedMock, Example.method(str, paramMock));
    }
}


来源:https://stackoverflow.com/questions/24516771/how-can-i-test-two-static-methods-one-invokes-the-other-with-powermockito

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!