MockServer -> Return custom object response

1.9k views Asked by At

I am trying to return custom object response from mockserver.

In client side, I am expecting to get response as "GetChannelsResponse".

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

Here is the model object of A:

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

I am trying to mock the response and return the custom object response as A.

I have tried below code:

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

But it seems like mockserver return only HttpResponse, not custom objects as response. In the above code, it return httpresponse and in body it pass the A object.

But in client, as shown above i am expecting to response as A.

Please suugest some suggestions to achieve it

1

There are 1 answers

0
Stackflow On

Add in return response as withcontenttype as MediaType.APPLICATION_JSON

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