Search code examples
javaunit-testingtestngjmockit

Jmockit: Expectations() works in v12 but not in v13/v14 (Java SE 8, TestNG 6.8.13)


With JMockit v12, this test passes (not the real code, but illustrates the issue):

import mockit.Expectations;
import mockit.Mocked;
import org.testng.Assert;
import org.testng.annotations.Test;

public class JmockitExperimentsTest2
{
  public class MyClass
  {
    public int getValue()
    {
      return 5;
    }
  }
  @Mocked
  MyClass myClass;

  @Test ()
  public void jmockitTest()
  {

    new Expectations()
    {
      {
        myClass.getValue();
        returns(8);
        myClass.getValue();
        returns(4);
      }
    };
    Assert.assertEquals(myClass.getValue(), 8);
    Assert.assertEquals(myClass.getValue(), 4);
  }
}

With JMockit v13 (and v14) it gets this assertion failure:

java.lang.AssertionError: expected [8] but found [4]

I get the same assertion failure in v13/v14 if I use "NonStrictExpectations" in place of "Expectations". However, if I change "Expectations" to "StrictExpectations" in v13/v14, there is no assertion failure.

I see from the JMockit change log that changes were made to the Expectations in v13 so presumably, I don't understand the description in the change log about what to expect. But it seems this change is not backward compatible.

It's very confusing to me why "Strict" works and "NonStrict" doesn't -- I'd expect anytime "Strict" succeeds, "NonStrict" would also succeed.

What am I doing wrong?


Update:

Using Rogério's answer, the following change eliminates the problem:

new Expectations()
{
  {
    myClass.getValue();
    returns(8, 4);
  }
};

Solution

  • The test fails because it redundantly records the same expectation twice. Instead, record it once by calling returns with the entire sequence of desired return values, as it is a varargs method.

    The semantics changes in JMockit 1.13 were made to prevent mistakes line this, but the validation against duplicate expectations is still an open issue, to be fixed in version 1.15.