【发布时间】:2013-05-03 18:20:11
【问题描述】:
我目前在 JUnit 测试中遇到困难,需要一些帮助。所以我得到了这个带有静态方法的类,它将重构一些对象。为了简单起见,我做了一个小例子。这是我的工厂课程:
class Factory {
public static String factorObject() throws Exception {
String s = "Hello Mary Lou";
checkString(s);
return s;
}
private static void checkString(String s) throws Exception {
throw new Exception();
}
}
这是我的测试课:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Factory.class })
public class Tests extends TestCase {
public void testFactory() throws Exception {
mockStatic(Factory.class);
suppress(method(Factory.class, "checkString"));
String s = Factory.factorObject();
assertEquals("Hello Mary Lou", s);
}
}
基本上我试图实现的是私有方法checkString()应该被抑制(所以不会抛出异常),并且还需要验证方法checkString()实际上是在方法factorObject()中调用的。
更新: 抑制使用以下代码正常工作:
suppress(method(Factory.class, "checkString", String.class));
String s = Factory.factorObject();
...但是它为字符串“s”返回NULL。这是为什么呢?
【问题讨论】:
-
恕我直言,您使用该工具太过分了。不鼓励嘲笑被测类的想法。相反,您应该将值传递给您的测试方法,该方法将通过检查字符串通过和失败验证。这使您可以完全测试被测方法,而无需依赖其实现。你设计的是脆弱的测试。
-
我同意你的看法,但目前无法更改现有代码,因此验证必须稍微复杂一些。
标签: java junit powermock verify suppress