Custom exception message using JUnit assertEquals?

I use assert to compare two numbers

Assert.assertEquals("My error message", First , Second); 

Then, when I create a test report, I get

"My error message (first) was (second)"

How can I customize the part in italics? And the number format?

+6
source share
3 answers

You can use something like this:

 int a=1, b=2; String str = "Failure: I was expecting %d to be equal to %d"; assertTrue(String.format(str, a, b), a == b); 
+8
source

The message is hardcoded in the Assert class. You will need to write your own code to create a special message:

 if (!first.equals(second)) { throw new AssertionFailedError( String.format("bespoke message here", first, second)); } 

(Note: the above example - you need to check the zeros, etc. See Assert.java code to find out how to do this).

+5
source

Thanks to your answer, I found in the Assert class this

  static String format(String message, Object expected, Object actual) { String formatted= ""; if (message != null && !message.equals("")) formatted= message + " "; String expectedString= String.valueOf(expected); String actualString= String.valueOf(actual); if (expectedString.equals(actualString)) return formatted + "expected: " + formatClassAndValue(expected, expectedString) + " but was: " + formatClassAndValue(actual, actualString); else return formatted + "expected:<" + expectedString + "> but was:<" + actualString + ">"; } 

I think I cannot change the Junit Assert class, but I can create a new class in my project with the same name, just changing the format, right? Or can I just change the format in my class and this will affect the throw of an Exception?

0
source

Source: https://habr.com/ru/post/944886/


All Articles