5 ms·
This can be improved, it'd be worth Googling for a better solution than what you have. https://github.com/skyscreamer/JSONassert https://github.com/skyscreamer
by david_allison 4y ago
This can be improved, it'd be worth Googling for a better solution than what you have.
https://github.com/skyscreamer/JSONassert https://github.com/skyscreamer/JSONassert seems decent.
but it can be done from scratch in a few hours (I'd recommend this if you have 'standardized' fields which you may want to ignore):
Move to a matcher library for assertions (Hamcrest is decent), and abstract `toJSON` into the a matcher, rather on the input.
This would change the assertion from:
`assertEquals(toJson(someObject), giantJsonBlobFromADifferentFile)`
to:
`assertThat(someObject, jsonEqual(giantJsonBlobFromADifferentFile))`
The difference here is subtle: it allows `jsonEqual` to control the formatting of the test failure output, so on a failure you can:
* convert both of the strings back to JSON
* perform a diff, and provide the diff in the test output.
Decent blog post on the topic: https://veskoiliev.com/use-custom-hamcrest-matchers-to-level-up-your-tests/ https://veskoiliev.com/use-custom-hamcrest-matchers-to-level...
- Macha 4y agoSo the same team does actually use JSONAssert in some places, but it can still provide unhelpful comparisons. I'd actually rather people just assert on the fields they need, but it's a larger team than I can push that on.
- david_allison 4y agoFrom a "legacy code" perspective, you're better off picking an 'easy win' (Hamcrest). Initially, you're not going to convince a team to change their testing habits if it causes them pain. Your goal is to push a testing methodology which moves closer to the 'ideal' which saves them time. Hamcrest is a drop-in replacement for `assertEquals`, and provides obvious benefits. Politically, it's easy to convince developers onboard once you show them: * You just need to change the syntax of an assertion - no thought required * You (Macha) will take responsibility for improving the formatting of the output, and developers have someone to reach out to to improve their assertions. From this: you'll get a very small subset of missionaries who will understand the direction that you're pushing the test code in, and will support your efforts (by writing their own matchers and evangelising). The larger subset of the developer population won't particularly care, but will see the improved output from what you're proposing, and will realise that it's a single line of code to change to reap the benefits. EDIT: I've added a lint rule into a codebase to guide developers away from `assertEquals()`. Obviously this could backfire, and don't burn your political capital on this issue.