Ignoring whitespace AND newlines with AssertJ

668 views Asked by At

I have a unit test for a Java application that needs to compare two JSON strings. I only care about the data, the formatting should be ignored. I was hoping I could use AssertJ, but I can't seem to figure out how. I need to ignore both the whitespace AND the newlines in my assertion. AssertJ has methods 'isEqualToIgnoringNewLines()' and 'isEqualToIgnoringWhitespace()' but I can only use one or the other. There doesn't seem to be any way to combine them to get the desired result.

My workaround for the moment is to strip out the whitespace myself before running the assertion. However, I feel like there should be a way to do this with just assertions. Is there any way to get the kind of assertion I want without having to manipulate the strings first?

3

There are 3 answers

0
Trung Nguyen On

I can only offer workaround by using JSONAssert to achieve comparison that ignores whitespaces and newlines for unit test.

import org.skyscreamer.jsonassert.JSONAssert;

JSONAssert.assertEquals(expect, result, JSONCompareMode.LENIENT);

Hope this helps!

0
Stefano Cordio On

JsonUnit might help. With the AssertJ integration, you could write:

import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;

...

// compares two JSON documents (note lenient parsing of expected value)
assertThatJson("{\"a\":1, \"b\":2}").isEqualTo("{b:2, a:1}");
0
Basile Jean On

With AssertJ (>2.8.0 according to the javadoc) to compare two strings whithout taking care of whitespaces (including newlines) you have to simply use method isEqualToIgnoringWhitespace.

This method uses isWhitespace(char ch) from java.lang.Character to dertermine what is a whitespace. \r and \n are whitespaces according to the javadoc (JDK21 | JDK8).