How make JUnit to print asserts and results

2020-05-18 11:15发布

问题:

I have some tests like this:

@Test
public void test01()
{
    Position p = getPositionAt('a', 1);
    assertNotNull("a1 exists", p);
    assertNotNull("figure exists a1", p.getFigure());

    p = getPositionAt('a', 2);
    assertNotNull("exists a2", p);
    assertNull("figure exists a2", p.getFigure());

    p = getPositionAt('b', 1);
    assertNotNull("exists b1", p);
    assertNull("figure exists b1", p.getFigure());
}

What I need while running tests is to print each assert message to stdout and then result of the assert.

This is require format from test class:

a1 exists -success
figure exists a1 -success
exists a2 -success
figure exists a2 -succcess
exists b1 -succcess
figure exists b1 -failed

But how to do that? I'm quite a new working with JUnit and have no idea. Is there way using runners and suites? Or exist any assertSuccess(), assertFailed() methods? Thanks for any hint.

回答1:

First, you have two issues not one. When an assertion fails, an AssertionError exception is thrown. This prevents any assertion past this point from being checked. To address this you need to use an ErrorCollector.

Second, I do not believe there is any way built in to JUnit to do this. However, you could implement your own methods that wrap the assertions:

public static void assertNotNull(String description, Object object){
     try{
          Assert.assertNotNull(description, object);
          System.out.println(description + " - passed");
     }catch(AssertionError e){
          System.out.println(description + " - failed");

        throw e;
     }
}


回答2:

All the assertXXX methods have a form that allows for displaying a String on error:

assertNotNull("exists a2", p); // prints "exists a2" if p is null

There is no particular value in printing a message on success.

EDIT

Junit typically provides 2 forms of an assert. To follow the example above, you can test for a null value in 1 of 2 ways:

assertNotNull(p)

or

assertNotNull("my message on failure", p)

The framework will print the error messages with no other effort required by you (it's provided by the framework).

To test for exceptions you would use the following pattern:

try{
    someCall();
catch(Exception e){
    fail(): // exception shouldn't happen, use assertTrue(true) if it should
}

Again, there are versions of these methods for adding a message

Check the API



回答3:

One last resort option is to pair each assert with a corresponding System.out.println, though obviously that is less than ideal. Still, it will solve the problem if all else fails.