如何使JUnit打印断言和结果 [英] How make JUnit to print asserts and results

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

问题描述

我有一些这样的测试:

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

运行测试时我需要的是将每个断言消息打印到stdout然后断言的结果。

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

但是怎么做?我是JUnit的新工作者并不知道。有没有办法使用跑步者套房?或者存在任何 assertSuccess() assertFailed()方法?感谢任何提示。

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.

推荐答案

首先,你有两个问题而不是一个。当断言失败时,抛出 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天全站免登陆