Skip to main content

Posts

Showing posts with the label JavaTip

Wildcard in assertions error messages

Assume that you want to compare whether 2 numbers are equal or not. Most of us would do it like: @Test public void testCompare() { int x = 92; int y = 99; Assert.assertTrue("x is not equal to y", x == y); } And as we can see that these numbers aren't equal, so we'll get the error in this case. But it is not clear at all why the assertion fails as the values of x and y are not included in the failure message. FAILED: testCompare AssertionError: x is not equal to y Is there a way we can improve the message so that we can get the complete info from the error message itself? Yes, how about using wildcards in the error message: @Test public void testCompare() { int x = 92; int y = 99; String notEqualMsg = "%d is not equal to %d"; Assert.assertTrue(String.format(notEqualMsg, x, y), x == y); } FAILED: testCompare AssertionError: 92 is not equal to 99 Tada...problem solved!!! hashtag # easier hashtag # betterway hashtag # sele...