0

我正在尝试从 mockserver 返回自定义对象响应。

在客户端,我希望得到响应为“GetChannelsResponse”。

 ResponseEntity<A> response = restTemplate.exchange(url, HttpMethod.GET, request, A.class);

这是A的模型对象:

public class A{
    private String resultCode;
    private String errorCode;
    private String errorDescription;
    private Integer totalResults;
    private List<B> b= new ArrayList();
}

我正在尝试模拟响应并将自定义对象响应作为 A 返回。

我试过下面的代码:

mockServer.when(
                request()
                        .withPath("/[a-z]+/[a-z]+/[0-9]+")
        )
                .respond(
                        httpRequest -> {
                            String method = httpRequest.getMethod().getValue();
                            String path = httpRequest.getPath().getValue();
                            Integer id = Integer.valueOf(getIdFromPath(path));

                            if (method.equals("GET")) { 
                                Channel channel = map.get(id);
                                A a= getOkGetResponse(Arrays.asList(channel));
                                if (channel != null) {
                                    return response()
                                            .withBody(
                                                    new ObjectMapper()
                                                            .writeValueAsString(
                                                                    channelsResponse
                                                            )
                                            )
                                            .withStatusCode(200);
}


private static A getOkGetResponse(List<Channel> channels) {
    A getResponse = new A();
    getResponse.setResultCode(HttpStatus.OK.name());
    getResponse.setTotalResults(channels.size());
    getResponse.setChannels(channels);

    return getResponse;
}

但似乎 mockserver 只返回 HttpResponse,而不是自定义对象作为响应。在上面的代码中,它返回 httpresponse 并在 body 中传递 A 对象。

但是在客户端,如上所示,我希望以 A 的形式响应。

请提出一些建议来实现它

4

1 回答 1

0

将返回响应添加为 withcontenttype 作为 MediaType.APPLICATION_JSON

                             return response()
                                        .withBody(
                                              new ObjectMapper().writeValueAsString(a)
                                        )
                                        .withStatusCode(200)
                                        .withContentType(MediaType.APPLICATION_JSON);
于 2020-12-28T12:54:43.553 回答