Stephan
Stephan

Reputation: 1999

Show result of failed JUnit tests in the console

In a JUnit (4.x) test case I want to get some log information in case one of the assertion fails. Assume this is the test class:

package a.b.c.d;

import org.junit.Assert;
import org.junit.Test;

public class SomeTestClass {

    @Test
    public void someSimpleTest() {
        Assert.assertEquals("123", "456");
    }
}

Obviously, Assert.assertEquals("123", "456"); will fail. When I run this test from within Eclipse I only get the Failure Trace with an exception. I would like to have some info printed onto the console about what actually failed, e.g.:

Expected Value: "123"; Actual Value "456";

Searching the internet I stumbled upon this example here that provides the information that I need. However, I'm not able to get this log output in the console.

org.junit.ComparisonFailure: expected:<gradle is gr[8]> but was:<gradle is gr[eat]>
    at org.junit.Assert.assertEquals(Assert.java:115)
    at org.junit.Assert.assertEquals(Assert.java:144)
    at com.mrhaki.gradle.SampleTest.sample(SampleTest.java:8)

What I tried so far is something like below, which didn't help.

-Djava.util.logging.ConsoleHandler.level=FINEST

static {
    Logger.getGlobal().setLevel(Level.FINEST);
}

Upvotes: 2

Views: 5434

Answers (2)

JohnK
JohnK

Reputation: 7337

According to the JUnit 4 documentation, there are other versions of assertEquals that take a message to be printed if the assertion fails:

public static void assertEquals(String message,
                                Object expected,
                                Object actual)

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.
Parameters:
message - the identifying message for the AssertionError (null okay)
expected - expected value
actual - actual value

Unfortunately I don't see a way to add the expected and actual values into that message, since it's just a predetermined string.

Upvotes: 0

flafoux
flafoux

Reputation: 2110

You can try catch ComparisonFailure :

@Test
public void someSimpleTest() {
    try {
      Assert.assertEquals("123", "456");
    } catch(ComparisonFailure e) {
      System.out.println(e.getMessage());
    }
}

You can also use getActual() and getExpected(). More doc here

Upvotes: 2

Related Questions