Java 如何嘲笑响应<&燃气轮机;使用泛型类型?
我需要模拟一个服务。在模拟类时,我在Java 如何嘲笑响应<&燃气轮机;使用泛型类型?,java,web-services,spring-boot,junit,mockito,Java,Web Services,Spring Boot,Junit,Mockito,我需要模拟一个服务。在模拟类时,我在ResponseEntityresp中得到null 需要模拟的方法: public List<Expression> getExpression(String expressView, Localdate date) { List<Expression> =new ArrayList<>(); Map<String, Object> uri = new HashMap<>();
ResponseEntity
resp中得到null
需要模拟的方法:
public List<Expression> getExpression(String expressView, Localdate date) {
List<Expression> =new ArrayList<>();
Map<String, Object> uri = new HashMap<>();
UriComponenetsBuilder build =
UriComponentsBuilder.fromHttpUrl("someUrl" + "/" + expressView);
build.queryParam(someParameter, someParameter);
build.queryParam(someParameter, someParameter);
build.queryParam(someParameter, someParameter);
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_JSON);
RestClient client = new RestClient(
build.build().encode.toUriString, HttpMethod.GET.Uri, header
);
ResponseEntity<?> resp = restC.SomeMethod(client);
if (resp = !null) {
//it goes to these line
}
}
所以上面的方法调用服务获取一些数据获取expressView的值并另存为列表。当我模仿方法when(restC.SomeMethod(client)),然后返回(resp)
它命中了URL,但作为responseresp
得到的值为空。
所以这里我得到的resp
值为null
。我在postman中检查了URL(someUrl),它返回了值
如何模拟响应属性
谢谢。首先,创建一个
ResponseEntity
对象:
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_JSON);
ResponseEntity<?> responseEntity = new ResponseEntity<>(
"some response body",
header,
HttpStatus.OK
);
when(restC.SomeMethod(client)).thenReturn(responseEntity);
注意事项: 避免在
@服务类
中使用响应属性
。您应该在@RestController class
中使用ResponseEntity
您可以使用@Autowired
注释插入您的@Service class
,如:
@RestController
public class YourControllerClass {
@Autowired
private YourServiceClass yourServiceClass;
或者使用构造函数
,例如:
@RestController
public class YourControllerClass {
private YourServiceClass yourServiceClass;
public YourControllerClass(YourServiceClass yourServiceClass) {
this.yourServiceClass= yourServiceClass;
}
因此:
@Service class
将处理业务或数据对象
,@RestController class
将处理响应
和请求
对象。因此,我们有单一责任原则
一些不错的链接:
希望这有帮助 可能重复Hi,@J.Macedo我尝试了这个示例,但仍然得到空值。我用建议、示例和一些不错的链接改进了我的答案;)我希望这对你有帮助。
@RestController
public class YourControllerClass {
private YourServiceClass yourServiceClass;
public YourControllerClass(YourServiceClass yourServiceClass) {
this.yourServiceClass= yourServiceClass;
}