我需要模拟服务。我在模拟类时在ResponseEntity<?>
响应中为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
}
}
在我的模拟方法中:
when(restC.SomeMethod(client)).thenReturn(resp);
因此,上述方法调用服务获取一些数据,获取expressView的值并另存为列表。当我嘲笑方法
when(restC.SomeMethod(client)).thenReturn(resp);
时,它命中了URL,但我作为响应resp
获得的值为null。所以在这里,我将
resp
的值设置为null
。我检查了邮递员中的URL(someUrl)返回值。如何模拟
ResponseEntity<?>
?谢谢。
最佳答案
首先,创建一个ResponseEntity
对象:
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_JSON);
ResponseEntity<?> responseEntity = new ResponseEntity<>(
"some response body",
header,
HttpStatus.OK
);
然后构建一个模拟以返回
responseEntity
对象:when(restC.SomeMethod(client)).thenReturn(responseEntity);
注意点:
避免在
ResponseEntity
中使用@Service class
。您应该在ResponseEntity
中使用@RestController class
。您可以使用
Inject
注释@Service class
您的@Autowired
,例如:@RestController
public class YourControllerClass {
@Autowired
private YourServiceClass yourServiceClass;
或使用
constructor
,例如:@RestController
public class YourControllerClass {
private YourServiceClass yourServiceClass;
public YourControllerClass(YourServiceClass yourServiceClass) {
this.yourServiceClass= yourServiceClass;
}
所以:
@Service class
将处理business or data objects
,而@RestController class
将处理Response
和Request
对象。因此我们有Single Responsibility
原理。一些不错的链接:
Spring MVC - Using RequestEntity and ResponseEntity
How do I mock a REST template
Building REST services with Spring
Understanding the Single Responsibility Principle
希望这可以帮助!