2
votes

I am new to Junit and Jmockit. I wrote an example and want to test that using mocking, but I was stuck with an error.

public class First {

    public static int square(int number) {

        int result = number * number;
        return result;
    }
}

public class Second {

    public static void main(String[] args) {

        int number = 5;

        number = new Second().xi(number, number);
        System.out.println(number);
    }

    public int xi(int number, int number1) {
        number = First.square(number) + First.square(number1);
        return number;

    }

}

public class SecondTest {

    Second second = new Second();

    @Test
    public void testXi() {
        new Expectations() {

            {

                First.square(5);
                result = 25;
            }

        };
        int mk = second.xi(5, 5);
        assertEquals(50, mk);
    }
}

When I tried to run this SecondTest.java then i got the following error.

java.lang.IllegalStateException: Missing invocation to mocked type at this point; please make sure such invocations appear only after the declaration of a suitable mock field or parameter at SecondTest$1.(SecondTest.java:17) at SecondTest.testXi(SecondTest.java:12) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.lang.reflect.Method.invoke(Method.java:606) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.lang.reflect.Method.invoke(Method.java:606) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

I couldn't find any error in the code.

1
Where did you search, exactly? The JMockit documentation (Getting Started page, Tutorial, API docs) clearly say that types need to be mocked by using one of the mocking annotations before you can record expectations. Also, that is what the error message is saying: "...make sure such invocations appear only after the declaration of a suitable mock field or parameter".Rogério

1 Answers

2
votes

You should declare something like @Mocked First firstInstance in the test class (class level, not method level).

Then you need to make the expectation firstInstance.square(5); result = 25

This in essence tells jmockit that you want the First class to be mocked out, and that it should exchange all instances of the First class with the instance firstInstance. Then you tell it that you are expecting a call to this instance for the method xi(int, int) with the values 5, 5, and you want it to return 25 back.