Search code examples
javamockingjunit4jmockit

JMockit Returns Empty Object class


I am new to JMockit. I am trying to mock a class's method but the property are null. Examples below:

WebServiceUtility:

@Component
public class WebserviceUtility {


   public SamResponse getSamResponse(Parameters myParam) {

       return callWebService.postCall(myParam);;
    }
}

Service Class:

@Autowired
private WebserviceUtility webServiceUtility;

    public void checkResponse() {
       MyParam myParam = new MyParam();

      SamResponse samResponse = WebserviceUtility.getSamResponse(myParam);

      if (samResponse.getGoodResponse != null) {
        //Do things here
      }
    }

SamResponse class

public class SamResponse() {

 private GoodResponse goodResponse;
 private String error;
 //setters and getters here..

}

JMockit class:

public void testSamResponseGood() {

      final SamResponse samResponse = new SamResponse();
      GoodResponse res = new GoodResponse();
      samResponse.setGoodResponse(res);

      MyParam param = new MyParam();
      param.setAtt("test");

      new Expectations() {{ 

            webServiceUtility.getSamResponse(param); 
            result = samResponse ;
            times = 1;


        }};

}

When I try to check the value of the samResponse, the attributes - error and goodResponse are both null,even I passed the values in the new Expectations(){{}}; How can I return the actual object? What am I missing? Hope someone can give me some light. Thanks in advance.


Solution

  • I was able to fix my issue by the codes below. Using withInstanceOf(clazz) in the param and providing the actual object (above the new Expectataions) returned the actual object. My old code was, I was passing the actual instance of MyParam.class, then it returns the goodResponse object as expected.

    OLD CODE:

    MyParam params = new MyParams();
    param.setAtt("test");
    new Expectations() {{ 
    
            webServiceUtility.getSamResponse(params); 
            result = samResponse ;
            times = 1;
    
    
        }};
    

    FIXED CODE:

    public void testSamResponseGood() {
    
      final SamResponse samResponse = new SamResponse();
      GoodResponse res = new GoodResponse();
      samResponse.setGoodResponse(res);
    
    
      new Expectations() {{ 
    
            webServiceUtility.getSamResponse(withInstanceOf(MyParam.class)); 
            result = samResponse ;
            times = 1;
    
    
        }};
    

    }

    Hope this helps to other who would encounter the same issue.