下面是一个我很难弄清楚如何使用 JUnit 进行测试的方法。
此方法很难测试,因为它取决于其他方法(例如 getClosestDcoumentCode)的结果。
根据我对 JUnit 的阅读,这表明我应该重构该方法。但是怎么办?如果不需要重构,您如何测试依赖于其他方法的方法?
谢谢,
埃利奥特
private static String findPrincipal(List<DocumentKey> documentkeys_) {
Hashtable<String, Integer> codecounts = new Hashtable<String, Integer>();
for (DocumentKey document : documentkeys_) {
int x = 0;
String closestCode = getClosestDocumentCode(document.candidates);
if (closestCode == null) continue;
int thecount = 0;
if (codecounts.containsKey(closestCode))
thecount = codecounts.get(closestCode);
if (document.hasKey)
thecount += 2;
else
thecount++;
codecounts.put(closestCode, new Integer(thecount));
x++;
}
String closestCode = getClosestCode(codecounts);
return closestCode;
}
最佳答案
嗯,首先,我想知道方法是否真的需要是静态的,以及那个类在做什么。看起来它可能是一个 GOD 类,或者至少它违反了单一职责原则。 getClosestCode 有什么作用?如果它是一个类,您可以将它与测试中的 stub 一起注入(inject)到测试类中。
EasyMock 会让你模拟方法响应,但我不确定你如何模拟静态方法。
一般来说,你可能需要
- 将长函数提取到类中
- 使功能非静态
- 维护单一责任主体
关于java - 如何重构方法以使其更易于测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7303330/