Search code examples
mavenjmockit

JMockIt throws DuplicateExpectation in mvn when a test case has multiple expectations defined for the same static method


I'm trying to mock a web call that returns different results depending on the inputs.

My test case is as follows:

class RestService1 implements IRestService{

    public static String checkSomething(){
         return "something";
     }
}


class RestService2 implements IRestService{

    public static String checkSomething(){
        return "somethingElse";

    }
}


class TestClass {

    void test(){
        final RestService1 restServiceMock1=new RestService();

        new NonStrictExpectations() {
            @SuppressWarnings("unused")
            WebAPI webAPI; 
            {
                webAPI.getHandle( IRestService.class );
                result=restServiceMock1;
            }


        };

    String check=webAPI.getHandle.getSomething();

    //here check should have "something"

    //modify some data received as output

    final RestService2 restServiceMock2=new RestService();

    new NonStrictExpectations() {

        @SuppressWarnings("unused")

        WebAPI webAPI; 
        {
            webAPI.getHandle( IRestService.class );
            result=restServiceMock2;
        }

     };
     String check2=webAPI.getHandle.getSomething()
     //here check2 should have "somethingElse"

} 

Note: webAPI.getHandle() returns a fully loaded instance of IRestService that does webCall.

This testcase is giving me Duplicate Expectation error when run through maven using --javaagent:{jar location} However runs without any issues and as expected when run through Eclipse.

Is there some way to remove the expectation set first or some other change that can be done to override the initial Expectation with the next one?


Solution

  • The test method needs to be separated into two tests, one for RestService1 and another for RestService2.