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;
}

但似乎模拟服务器只返回 HttpResponse,而不是自定义对象作为响应。 在上面的代码中,它返回 httpresponse 并在正文中传递 A 对象。

但是在客户端,如上所示,我期望响应为 A。

请提出一些建议以实现它

解决方法

在返回响应中添加内容类型为 MediaType.APPLICATION_JSON

                             return response()
                                        .withBody(
                                              new ObjectMapper().writeValueAsString(a)
                                        )
                                        .withStatusCode(200)
                                        .withContentType(MediaType.APPLICATION_JSON);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...