简体   繁体   English

如何使用JMockit 1.31模拟非静态方法

[英]How to mock non static methods using JMockit 1.31

I am new to JMockit 1.31. 我是JMockit 1.31的新手。 Using JMockit, I am trying to write unit test scripts for the following code, However I am receiving assertion failure error. 使用JMockit,我试图为以下代码编写单元测试脚本,但是我收到断言失败错误。 Please help me to figure out the issue. 请帮助我找出问题所在。

Main class: ForUnit.java 主类: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;
    }
}

Dependent class: UnitHelper 相关类:UnitHelper

public class UnitHelper {
    private int a = 200;
    private int b = 100;

    public int getNumberA() {
        return a;
    }

    public int getNumberB() {
        return b;
    }
}

Unit test script using JMockit - ForUnitTest.java 使用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());
    }

}

You are creating a new UnitHelper in your test method which is not used in your ForUnit class. 您正在测试方法中创建一个新的UnitHelper ,而ForUnit类中没有使用该新方法。

You need a way to inject UnitHelper to your ForUnit so that you can mock its behavior. 您需要一种将UnitHelper注入到ForUnit以便可以模拟其行为。

You can try doing this: 您可以尝试这样做:

public class ForUnit {
  private UnitHelper unit = new UnitHelper();
  public ForUnit(UnitHelper unitHelper) {
     this.unit = unitHelper;
  }
  ...
}

And then in your test you can inject the helper object. 然后在测试中,可以注入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());
  }

UPDATE: 更新:

If you want to avoid creating a new constructor. 如果要避免创建新的构造函数。 You can use a setter method. 您可以使用setter方法。

public class ForUnit {
    private UnitHelper unit = new UnitHelper();
    setUnitHelper(UnitHelper unit) {
      this.unit = unit;
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM