简体   繁体   English

无法在JUnit4的@Override中捕获异常详细信息

[英]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.isElementPresent("//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. 我的问题是如何将错误消息“缺少第一张图片”传递给@Override ,以使其打印出该消息。

I'm a little confused as to why your MethodRule.failed method contains the statement assertTrue(false) . 关于您的MethodRule.failed方法为何包含语句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. Assert.assertTrue方法失败时,将引发java.lang.AssertionError ,并将消息值设置为您作为assertTrue方法的第一个参数提供的文本。 In order to retrieve that value you simply invoke the following: e.getMessage() . 为了检索该值,您只需调用以下代码: 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): 这是一个Method规则的示例,该规则将正在监视的测试的成功和失败结果输出到System.err(仅用作示例):

@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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM