How to assert json content in MockRestServiceServer?
Asked Answered
K

5

5

How can I tell MockRestServiceServer to expect a specific json content during a junit @Test?

I thought I could expect just a json string as follows: .andExpect(content().json(...)), but that method does not exist. So how could I rewrite the following?

private MockRestServiceServer mockServer;
private ObjectMapper objectMapper; //jackson

Person p = new Person();
p.setFirstname("first");
p.setLastname("last");

//mocking a RestTemplate webservice response
mockServer.expect(once(), requestTo("/servlet"))
        .andExpect(content().json(objectMapper.writeValueAsString(p))) //.json() does not exist! why?
        .andRespond(withSuccess(...));
Karisakarissa answered 14/3, 2018 at 16:35 Comment(0)
T
1

In spring-test version 5.0.5 the requested json method was added. Now, I am able to write

.andExpect(content().json(objectMapper.writeValueAsString(someDTO)))
Thermometer answered 19/6, 2023 at 8:20 Comment(0)
G
5

You can use for example:

 mockServer.expect(ExpectedCount.once(), requestTo(path))
                .andExpect(method(HttpMethod.POST))
                .andExpect(jsonPath("$", hasSize(1)))
                .andExpect(jsonPath("$[0].someField").value("some value"))
Gunrunning answered 30/7, 2018 at 13:25 Comment(0)
K
3

Seems your spring-test version is lower than 4.2

Have a look at https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/web/servlet/result/ContentResultMatchers.html#json-java.lang.String-boolean-

You can update your spring test dependency to be able to use the code that you have provided.

Keratosis answered 14/3, 2018 at 22:6 Comment(1)
Using spring-test-4.3.14.RELEASE. But what I noticed: the path of content() is org.springframework.test.web.client.match, not *.servlet.... That's because MockRestServiceServer is for mocking webservice responses through RestTemplate.Karisakarissa
G
2

It seems the ContentRequestMatcher object supports JSON strings starting with spring-test version 5.0.5.RELEASE.

Glycerol answered 28/3, 2019 at 21:10 Comment(0)
T
1

In spring-test version 5.0.5 the requested json method was added. Now, I am able to write

.andExpect(content().json(objectMapper.writeValueAsString(someDTO)))
Thermometer answered 19/6, 2023 at 8:20 Comment(0)
R
0

How about using jsonPath? andExpect(jsonPath("$.firstname", is("first")))

Raeraeann answered 14/3, 2018 at 18:59 Comment(1)
I want to create the json from a bean.Karisakarissa

© 2022 - 2024 — McMap. All rights reserved.