JUnit Assert Feature Interception

I want to do some “own things” when the statement 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 that were the case, that would be good, because every assert function like assertTrue()that calls the method fail(). That way, I could easily intercept every statement.

Is there any way to do what I want to do here without doing all the different options assert...?

+5
source share
3 answers

You should familiarize yourself with the Rules that were introduced in Junit 4.7. Especially TestWatchman:

TestWatchman - , . , :

http://junit-team.imtqy.com/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 depecreated Junit TestWatcher ( ):

http://junit-team.imtqy.com/junit/javadoc/4.10/org/junit/rules/TestWatcher.html

+3

, 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 .

+1

For individual statements, you can catch AssertionError - the following work for me. This is useful when you only need it from time to time.

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));
}
0
source

All Articles