【问题标题】:When to use @RunWith and when @ExtendWith何时使用 @RunWith 以及何时使用 @ExtendWith
【发布时间】:2019-08-12 01:53:58
【问题描述】:

我和我的团队一直在使用 Spring Boot 开发一堆微服务。 由于服务经历了 JUnit 和 Spring Boot 升级(我们现在使用的是 Spring Boot 2 和 JUnit 5),不同开发人员实现的不同 JUnit 现在使用不同的模式:

  • @ExtendWith
  • @RunWith

今天它们两者之间有什么区别?我们真的需要它们来进行单元测试还是嵌入到一些新的 Spring Boot 注释中?

【问题讨论】:

    标签: spring-boot annotations junit4 junit5


    【解决方案1】:

    如果你使用的是Junit版本@RunWith(SpringRunner.class)或@RunWith(MockitoJUnitRunner.class)等。

    如果您使用的是 Junit 版本 = 5,那么您必须使用 @ExtendWith(SpringExtension.class)@ExtendWith(MockitoExtension.class) 等。

    1. SpringRunner
    2. MockitoJUnitRunner
    3. SpringExtension
    4. MockitoExtension

    【讨论】:

      【解决方案2】:

      答案可以在documentation找到:

      如果您使用的是 JUnit 4,请不要忘记 将 @RunWith(SpringRunner.class) 添加到您的测试中,否则 注释将被忽略。如果您使用的是 JUnit 5,则无需 添加等效的 @ExtendWith(SpringExtension.class) 作为 @SpringBootTest 和 其他@…Testannotations 已经用它注释了

      .

      【讨论】:

        【解决方案3】:

        @RunWith 是来自 JUnit 4 的旧注释,用于使用测试运行器。如果您使用的是 JUnit 5 (Jupiter),则应使用 @ExtendWith 来使用 JUnit 扩展。

        【讨论】:

          猜你喜欢
          • 2012-03-13
          • 2015-01-07
          • 2016-09-23
          • 2021-02-09
          • 1970-01-01
          • 2020-01-11
          • 2011-01-18
          • 1970-01-01
          相关资源
          最近更新 更多