我需要模拟服务。我在模拟类时在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<?>
?
谢谢。
答案 0 :(得分:1)
First, create a ResponseEntity
object:
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_JSON);
ResponseEntity<?> responseEntity = new ResponseEntity<>(
"some response body",
header,
HttpStatus.OK // Or HttpStatus.ACCEPTED
);
Then build a mock:
when(restC.SomeMethod(client)).thenReturn(responseEntity);
Point to pay attention:
Avoid to use
ResponseEntity
inside@Service class
. You should useResponseEntity
in@RestController class
.
And you can Inject
you @Service class
using @Autowired
annotation, like:
@RestController
public class YourClass {
@Autowired
private YourClassService yourClassService;
So:
@Service class
will handlebusiness or data objects
and@RestController class
will handleResponse
andRequest
objects. Thus we haveSingle Responsibility
principle.
Some nice links:
希望这会有所帮助!