【问题标题】:ExpectedException with @Rule in junit test on eclipse IDE does not work在 Eclipse IDE 上的 junit 测试中使用 @Rule 的 ExpectedException 不起作用
【发布时间】:2020-10-20 04:58:42
【问题描述】:

我需要在junit中进行测试,如果抛出异常则通过,但一次又一次失败。

我在 stackoverflow 和其他来源中阅读了很多关于该主题的问题和答案。最终我看到了这个页面,它解释了 junit.org 的 ExpectedException 类的用法。

由于我无法进行自己的测试,因此我复制了他们的简单示例,但仍然无法正常工作。

这是我的代码:

import static org.junit.jupiter.api.Assertions.*;

import org.junit.Rule;
import org.junit.jupiter.api.Test;
import org.junit.rules.ExpectedException;

class AssertExceptionTest {
    
    @Rule
    public ExpectedException thrown= ExpectedException.none();

    @Test
    public void throwsNothing() {
        // no exception expected, none thrown: passes.
    }

    @Test
    public void throwsExceptionWithSpecificType() {
        thrown.expect(NullPointerException.class);
        throw new NullPointerException();
    }
}

引用我上面提到的页面,解释是“......在指定预期异常的类型后,当抛出此类异常时,您的测试成功,如果不同或否,则测试失败抛出异常...

问题是测试仍然失败,无论我做什么,它失败是因为我试图验证:抛出 NullPointerException。

我想可能是因为我使用的是 junit 5,所以我的测试失败了。但是,来自stackoverflow 的this question 提出了其他建议:提出问题的人提到他在eclipse 中使用junit 5 的方式与我在代码中的方式相同,成功。

技术细节: 日食版本:2019-12(4.14.0) junit 版本:junit 5 在 Ubuntu 上工作,版本:18.04.2 LTS。

更新: 我使用了 assertThrows(),它对我有用。但是,我仍然对上面描述的方法没有成功的原因感到困惑,这里有很多人建议。

提前致谢!

【问题讨论】:

    标签: eclipse junit rules expected-exception


    【解决方案1】:

    JUnit 5 不支持开箱即用的 JUnit 4 规则。

    使您的代码正常工作:

    1. 添加以下依赖项(当然,版本可能会随着时间而改变)
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-migrationsupport</artifactId>
        <version>5.5.2</version> 
        <scope>test</scope>
    </dependency>
    
    1. 接下来,将 @EnableRuleMigrationSupport 放在测试类的顶部。

    就是这样。请参阅this 了解更多信息。

    【讨论】:

    • 感谢@Mensur Qulami!我按照你的指示做了,效果很好!我以前从未使用过 Maven,所以对于任何会阅读本文但对 MAVEN 一无所知的人,this answer 上的解释对我有很大帮助,特别是 Oded Breiner 的回答和对 oded 的回答的悬崖 2310 评论
    猜你喜欢
    • 2015-07-08
    • 1970-01-01
    • 1970-01-01
    • 2010-12-03
    • 2016-03-30
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多