我是JMockit 1.31的新手。使用JMockit,我正在尝试为以下代码编写单元测试脚本,但是我收到了断言失败错误。请帮我弄清楚问题。
主类:ForUnit.java
public class ForUnit {
private UnitHelper unit = new UnitHelper();
public int add() {
return unit.getNumberA() + unit.getNumberB();
}
public int subtract() {
UnitHelper unit = new UnitHelper();
return unit.getNumberA() - unit.getNumberB();
}
public int subtractFromThird() {
return unit.getNumberA() - unit.getNumberB() + 10;
}
}
依赖类:UnitHelper
public class UnitHelper {
private int a = 200;
private int b = 100;
public int getNumberA() {
return a;
}
public int getNumberB() {
return b;
}
}
使用JMockit的单元测试脚本 - ForUnitTest.java
public class ForUnitTest {
private final int i =10, j=8;
@Tested
private ForUnit forUnit;
@Test
public void test() {
final UnitHelper helper = new UnitHelper();
new Expectations() {{
helper.getNumberA(); result = i;
helper.getNumberB(); result = j;
}};
assertEquals(i+j, forUnit.add());
}
}
答案 0 :(得分:1)
您正在测试方法中创建一个新的UnitHelper
,但ForUnit
类中未使用该<{1}}。
您需要一种方法将UnitHelper
注入ForUnit
,以便模仿其行为。
您可以尝试这样做:
public class ForUnit {
private UnitHelper unit = new UnitHelper();
public ForUnit(UnitHelper unitHelper) {
this.unit = unitHelper;
}
...
}
然后在测试中,您可以注入helper
对象。
@Test
public void test() {
final UnitHelper helper = new UnitHelper();
forUnit = new ForUnit(helper);
new Expectations() {{
helper.getNumberA(); result = i;
helper.getNumberB(); result = j;
}};
assertEquals(i+j, forUnit.add());
}
更新:
如果您想避免创建新的构造函数。您可以使用setter方法。
public class ForUnit {
private UnitHelper unit = new UnitHelper();
setUnitHelper(UnitHelper unit) {
this.unit = unit;
}
}