【发布时间】:2017-03-24 22:35:53
【问题描述】:
我正在尝试使用一堆静态方法测试一个实用程序类。我正在为调用另外两个静态方法的方法编写测试。在第一个静态方法调用模拟似乎工作,但它无视第二个期望并调用真实方法。任何想法?我尝试在第二个期望之前提供第二个 PowerMock.spy(Utils.class) 但没有运气。知道如何解决这个问题吗?
这里是示例代码。
package com.personal.test;
import java.io.IOException;
public class Utils {
public static String testUtilOne() {
System.out.println("Static method one");
return "methodone";
}
public static void testUtilsTwo(String s1, String s2, String s3) throws IOException {
throw new IOException("Throw an exception");
}
public static void testUtilsThree() throws TestException {
try {
String s = testUtilOne();
testUtilsTwo("s1", s, "s3");
} catch (IOException ex) {
throw new TestException("there was an exception", ex);
}
}
public static class TestException extends Exception {
public TestException() {
super();
}
public TestException(String message, Exception cause) {
super(message, cause);
}
}
}
package com.personal.test;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.personal.test.Utils.TestException;
@RunWith(PowerMockRunner.class)
@PrepareForTest({Utils.class})
public class UtilsTest {
@Test
public void testMethodThreeWrapsException() throws Exception {
PowerMockito.spy(Utils.class);
PowerMockito.when(Utils.class, "testUtilOne").thenReturn("This is coming from test");
PowerMockito.spy(Utils.class);
PowerMockito.when(Utils.class, "testUtilsTwo", Mockito.anyString(), Mockito.anyString(), Mockito.anyString()).thenThrow(new IOException("Exception from test"));
try {
Utils.testUtilsThree();
} catch (TestException ex) {
Assert.assertTrue(ex.getCause() instanceof IOException);
Assert.assertEquals("Exception from test", ex.getMessage());
}
}
}
【问题讨论】:
-
仅作记录:仅在必要时仅使用 Power 框架进行静态模拟。大多数时候人们要求 Powermock ......那是因为他们创建了难以/不可能测试的代码;他们认为使用 Powermock 可以解决这个问题。不,它不会。真正的答案是应用良好的 OO 技术而不使用 Powermock ;-.)
标签: unit-testing junit mockito powermock powermockito