如何测试第一个静态方法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) {
// ...
}
}
我尝试使用下面的代码进行测试
@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();
}
但没有运气。我如何修复例如此测试来验证第二种方法的调用?
答案 0 :(得分:0)
此代码有效:
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));
}
}