Search code examples
junitjmockitexpectations

Issue with NonStrictExpections to Expectations conversion in junit test cases


Here is my sample code example, which starts failing when I made jmockit update related changes.

class A {

    public static boolean validate(String name, int age, boolean flag) {
        boolean result = false;
        //actual code
        return result;
    }
}

class B {
    public void cal() {
        if (A.validate(name, age, flag)) {
            // some calculations
        }
    }
}

class TestB {
    public B b;

    @Before
    public void setUp() {
        b = new B();
    }

    @Test
    public void testCal() {
        new Expectations() {
            {
                A.validate(anyString, anyInt, anyBoolean);
                times= -1;
                result = Boolean.TRUE;
            }};

        b.cal();

        new Verifications() {
            {
                A.validate(anyString, anyInt, anyBoolean);
            }
        };
    }
}

This is failing with error

mockit.internal.UnexpectedInvocation: Unexpected invocation of:
A#validate(String name, int age, boolean flag)

I just changed NonStrictExpectations block to Expectations block, because latest jmockit dont support NonStrictExpectations block.

new NonStrictExpectations() {
    {
        A.validate(anyString, anyInt, anyBoolean);
        returns(Boolean.TRUE);
    }
};

With this block everything works fine.

Please let me know where is the issue?


Solution

  • First of all, using a negative value for the times is not a valid value.

    Second, if what you need is to have an optional call, you should use the minTimes and maxTimes variables. In your case with maxTimes = 1 you will achieve an optional mocked call.