Lorm
Lorm

Reputation: 237

Custom exception message using JUnit assertEquals?

I'm using assert equals to compare two numbers

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

Then, when I generate the Test Report I get

"My error message expected (First) was (Second)"

How can I customize the part I've put in italic? And the format of the numbers?

Upvotes: 13

Views: 32845

Answers (3)

Lorm
Lorm

Reputation: 237

Thanks to your answer I've 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 guess I can't modify Junit Assert class, but I can create a new class in my project with the same name, just changing format, am I right? Or I can just change format in my class and it will affect the Exception thrown?

Upvotes: 0

Salem
Salem

Reputation: 12986

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);

Upvotes: 9

Duncan Jones
Duncan Jones

Reputation: 69339

The message is hard-coded in the Assert class. You will have to write your own code to produce a custom message:

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

(Note: the above is a rough example - you'll want to check for nulls etc. See the code of Assert.java to see how it's done).

Upvotes: 7

Related Questions