如何使JUnit打印断言结果 [英] How make JUnit print assertion results

查看:106
本文介绍了如何使JUnit打印断言结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取要打印到[标准输出]的JUnit断言的结果?

How can I get the results of my JUnit assertions to be printed [to standard output]?

我有一些像这样的测试:

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

这是我希望获得的打印输出格式:

This is the printed output format I am hoping to get:

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

是否可以使用runnerssuites来做到这一点?还是存在任何assertSuccess()assertFailed()方法?

Is there way to do this using runners and suites? Or does there exist any assertSuccess(), assertFailed() methods?

推荐答案

首先,您有两个问题,而不是一个.断言失败时,将抛出AssertionError异常.这样可以防止检查超过此点的任何断言.要解决此问题,您需要使用 ErrorCollector .

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.

第二,我不认为JUnit内置了任何方法来执行此操作.但是,您可以实现自己的用于包装断言的方法:

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

这篇关于如何使JUnit打印断言结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆