问题
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