Reputation: 86687
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(...));
Upvotes: 5
Views: 8411
Reputation: 59
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)))
Upvotes: 1
Reputation: 430
It seems the ContentRequestMatcher object supports JSON strings starting with spring-test version 5.0.5.RELEASE.
Upvotes: 2
Reputation: 126
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"))
Upvotes: 5
Reputation: 452
Seems your spring-test version is lower than 4.2
You can update your spring test dependency to be able to use the code that you have provided.
Upvotes: 3
Reputation: 25936
How about using jsonPath? andExpect(jsonPath("$.firstname", is("first")))
Upvotes: 0