开发者

Cannot capture exception details in @Override in JUnit4

@Rule
public MethodRule watchman = new TestWatchman() {
    @Override
    public void failed(Throwable e, FrameworkMethod method) {
        try {
            System.out.println("Exception =" + e.getClass().getSimpleName());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        assertTrue(false);
    }
};

The code that causes the failure is :

assertTrue("Missing first picture",selenium.isElementPresen开发者_Go百科t("//div/a/img[2]"));   

My question is how do I pass the error message "Missing first picture" to the @Override so that it prints out that message.


I'm a little confused as to why your MethodRule.failed method contains the statement assertTrue(false). For the sake of this discussion I will assume that you added that statement for testing and then did not remove it for this post.

The Assert.assertTrue method, when fails, causes a java.lang.AssertionError to be thrown with it's message value being set to the text you supplied as the first parameter to the assertTrue method. In order to retrieve that value you simply invoke the following: e.getMessage().

Here is an example of a Method rule that prints out the success and failure results of the tests being monitored to System.err (used as example only):

@Rule
public MethodRule watchman = new TestWatchman() {
    @Override
    public void failed(Throwable e, FrameworkMethod method) {
        System.err.println(method.getName() + "() failed with error: " + e.getMessage());
    }

    @Override
    public void succeeded(FrameworkMethod method) {
        System.err.println(method.getName() + "() succeeded");
    }
};

If you use this example with the following tests:

@Test
public void test1() {
    assertTrue("will not happen", true);
}

@Test
public void test2() {
    assertTrue("My error message", false);
}

You will see the following:

test1() succeeded
test2() failed with error: My error message
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜