membersound
membersound

Reputation: 86687

How to assert json content in MockRestServiceServer?

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

Answers (5)

Jan Baudisch
Jan Baudisch

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

Nathan Blake
Nathan Blake

Reputation: 430

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

Upvotes: 2

Omri Aviv
Omri Aviv

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

Sergey Sargsyan
Sergey Sargsyan

Reputation: 452

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.

Upvotes: 3

Lesiak
Lesiak

Reputation: 25936

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

Upvotes: 0

Related Questions