我是JMockit的新手。我正在尝试模拟类的方法,但该属性为null。以下示例:
WebServiceUtility:
@Component
public class WebserviceUtility {
public SamResponse getSamResponse(Parameters myParam) {
return callWebService.postCall(myParam);;
}
}
服务等级:
@Autowired
private WebserviceUtility webServiceUtility;
public void checkResponse() {
MyParam myParam = new MyParam();
SamResponse samResponse = WebserviceUtility.getSamResponse(myParam);
if (samResponse.getGoodResponse != null) {
//Do things here
}
}
SamResponse类
public class SamResponse() {
private GoodResponse goodResponse;
private String error;
//setters and getters here..
}
JMockit类:
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;
}};
}
当我尝试检查samResponse的值时,即使我在新的Expectations(){{}}中传递了值,属性-error和goodResponse都为空。如何返回实际对象?我想念什么?希望有人能给我一点光。预先感谢。
答案 0 :(得分:0)
我可以通过以下代码解决问题。 在参数中使用withInstanceOf(clazz)并提供实际对象(在新的Expectataions之上)将返回实际对象。 我以前的代码是,我正在传递MyParam.class的实际实例,然后它按预期返回了goodResponse对象。
旧代码:
MyParam params = new MyParams();
param.setAtt("test");
new Expectations() {{
webServiceUtility.getSamResponse(params);
result = samResponse ;
times = 1;
}};
固定代码:
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;
}};
}
希望这对遇到相同问题的其他人有所帮助。