How make JUnit to print asserts and results

泄露秘密 提交于 2019-12-02 18:01:48
John B

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!