A Java text block is an easy way to have a multiline string value.
But there is a catch if we want to use a text block with the assertion method isEqualTo.
Suppose you have written a piece of code that create a new string value where the line endings are defined using System.lineSeparator().
The string value would have the line ending \n on Linux and MacOS systems, and the line ending \r\n on Windows system.
But a Java text block will always use the line ending \n on every platform, including the Windows platform.
If you would run your tests on a Windows platform then the assertion using isEqualTo will fail, but the test will pass on Linux or MacOS systems.
This is a problem if you are working with developers using different operating systems.
Therefore it is better to use the method isEqualToNormalizingNewlines for these type of assertions.
AssertJ will make sure the line endings are the same and the tests will pass independent of the operating system the tests are run on.
In the following example you can see usage of the isEqualToNormalizingNewlines method:
package mrhaki;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class TextBlock {
@Test
void shouldEqualWithNormalizingLines() {
var text = "Generated text with multiple lines"
+ System.lineSeparator()
+ "separated by the platform specific line ending."
+ System.lineSeparator()
+ "On Windows \r\n and on Linux and MacOS \n.";
var expected =
"""
Generated text with multiple lines
separated by the platform specific line ending.
On Windows \r\n and on Linux and MacOS \n.""";
// assertThat(text).isEqualTo(expected); fails when this
// test is run on a Windows machine, because the line ending
// in a Java text block is always \n, even on a Windows machine.
// It is safer to use isEqualToNormalizingNewLines if the assertion
// is done with a Java text block.
assertThat(text).isEqualToNormalizingNewlines(expected);
}
}
Written with AssertJ 3.27.6