[英]How to mock non static methods using JMockit 1.31
我是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());
}
}
您正在测试方法中创建一个新的UnitHelper
,而ForUnit
类中没有使用该新方法。
您需要一种将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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.