Vishwa Dany
Vishwa Dany

Reputation: 327

How to mock non static methods using JMockit 1.31

I am new to JMockit 1.31. Using JMockit, I am trying to write unit test scripts for the following code, However I am receiving assertion failure error. Please help me to figure out the issue.

Main class: 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

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

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());
    }

}

Upvotes: 0

Views: 480

Answers (1)

alayor
alayor

Reputation: 5025

You are creating a new UnitHelper in your test method which is not used in your ForUnit class.

You need a way to inject UnitHelper to your ForUnit so that you can mock its behavior.

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.

 @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.

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

Upvotes: 1

Related Questions