Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 318
Lorm Avatar asked May 13 '13 14:05

Lorm


People also ask

How do you assert an exception in JUnit?

When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.

What is the use of assertEquals in JUnit?

assertEquals. Asserts that two objects are equal. If they are not, an AssertionError is thrown with the given message. If expected and actual are null , they are considered equal.

What is assert assertFalse ()?

In assertFalse, you are asserting that an expression evaluates to false. If it is not, then the message is displayed and the assertion fails. assertTrue (message, value == false) == assertFalse (message, value); These are functionally the same, but if you are expecting a value to be false then use assertFalse .


2 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);
like image 121
Salem Avatar answered Oct 23 '22 07:10

Salem


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

like image 44
Duncan Jones Avatar answered Oct 23 '22 07:10

Duncan Jones