5

I would like to do some "own stuff" when an assertion in JUnit fails. I would like to have this:

public class MyAssert extends org.junit.Assert {

    // @Override
    static public void fail(String message) {
        System.err.println("I am intercepting here!");
        org.junit.Assert.fail(message);
    }
}

Of course, this does not work, because you cannot override static methods. But if it would, this would be nice, because every assert function like assertTrue() calls the fail() method. Thus, I could easily intercept every assertion.

Does there exist any way to do what I want to do here, without implementing all different flavors of assert...?

4

4 回答 4

4

您应该查看在 Junit 4.7 中引入的规则。特别是TestWatchman:

TestWatchman 是记录测试操作的规则的基类,无需修改它。例如,此类将保留每个通过和失败测试的日志:

http://junit-team.github.io/junit/javadoc/4.10/org/junit/rules/TestWatchman.html

它允许您定义一个 MethodRule 来处理失败的测试(从 javadoc 复制):

   @Rule
    public MethodRule watchman= new TestWatchman() {
            @Override
            public void failed(Throwable e, FrameworkMethod method) {
                    watchedLog+= method.getName() + " " + e.getClass().getSimpleName()
                                    + "\n";
            }

            @Override
            public void succeeded(FrameworkMethod method) {
                    watchedLog+= method.getName() + " " + "success!\n";
            }
    };

    @Test
    public void fails() {
            fail();
    }

    @Test
    public void succeeds() {
    }

根据评论 TestWatchman 在较新版本的 Junit 中被取消并替换为 TestWatcher (但功能相同):

http://junit-team.github.io/junit/javadoc/4.10/org/junit/rules/TestWatcher.html

于 2011-03-25T16:42:16.377 回答
1

您可以编写一个类来实现 Assert 中所有方法的完全相同的签名,然后委托给 Assert 方法。

public class MyAssert {
    static public void assertTrue(String message, boolean condition) {
        Assert.assertTrue(message, condition);
    }

    ...

    static public void fail(String message) {
        System.err.println("I am intercepting here!");
        Assert.fail(message);
    }
}

不完全重新实现所有方法,但仍然很乏味。您的 IDE 可能有助于生成委托方法。

于 2011-03-25T00:09:54.247 回答
0

对于个人断言,您可以捕获 AssertionError - 以下对我有用。当您只是偶尔需要该功能时,它很有用。

try {
    Assert.assertEquals("size", classes.length, containerList.size());
} catch (AssertionError e) {
    System.err.println("ERROR");
    for (AbstractContainer container : containerList) {
        System.err.println(container.getClass());
    }
    throw (new RuntimeException("Failed", e));
}
于 2013-08-16T09:17:36.030 回答
0

TestWatchman 被 TestWatcher 取代,它在测试方法级别而不是 Assert 级别拦截,并且 Assert 类静态方法不能被覆盖,因此另一种方法是创建自己的断言方法来断言对象,该方法应该适用于大多数断言

于 2022-02-20T11:51:27.147 回答