1

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);
}
Stephan
  • 1,791
  • 1
  • 27
  • 51
  • 1
    Here is something about it http://stackoverflow.com/questions/1119385/junit-test-for-system-out-println – newuserua_ext Apr 09 '15 at 09:14
  • @newuserua_ext Maybe I misunderstood this thread but I don't want to test the console output. I just want to see JUnit log output in the console. – Stephan Apr 09 '15 at 09:19

2 Answers2

2

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

JohnK
  • 6,865
  • 8
  • 49
  • 75
flafoux
  • 2,080
  • 1
  • 12
  • 13
0

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.

JohnK
  • 6,865
  • 8
  • 49
  • 75