k13i
k13i

Reputation: 4331

MockMvcResultMatchers - jsonPath() vs content()

I'm testing Spring REST controllers using org.springframework.test.web.servlet.MockMvc object. I can verify response JSON using MockMvcResultMatchers.content() method or MockMvcResultMatchers.jsonPath() method which accepts Hamcrest matcher. I'm wondering which approach is better and what are the best practices? With complicated structure Hamcrest matchers seems really hard to read, and with content(), long JSON has to be externalized to separate file (but it's not big deal IMHO). Should I prefer one option to another or it's completely personal thing?

Upvotes: 1

Views: 2196

Answers (2)

dehasi
dehasi

Reputation: 2773

You can use content() when your response is not JSON. I.e. if the response is a plain text.

jsonPath() gives you more opportunities to check the response. For example

  • you need only check a particular field;

  • you need to check json-array, but you don't care about ordering;

  • you compare for greater/less, but not exact matching,

Upvotes: 1

Loïc Le Doyen
Loïc Le Doyen

Reputation: 1055

It depends on the payload you are manipulating.

If the payload is a short String with no moving values (like dates, etc.), you can go with plaintext comparison, maybe written using hjson to improve readability.

On the other hand, if you have to test complex payloads, jsonPath are a good way to ease test reading.

In many cases, asserting that the payload is compliant with your json-schema is sufficient, as your business rules is tested in your domain package, so you just have to test the mapping from business objects to DTO.

In the rare case a majority of your tests are about testing JSON content, you may want to go with a specialized comparison tool like JsonUnit and store payload templates in files.

In fine, if you are unit-testing (as in a test per method case), the only thing you are testing using MockMvcResultMatchers#... is the integration of your code with spring-mvc conventions.

Upvotes: 1

Related Questions