JUnit5 @RunWith
最后更新:2025年8月13日
1. 简介
在本快速教程中,我们将讨论在 JUnit 5 框架中使用@RunWith 注解。
在 JUnit 5 中,@RunWith 注解已被功能更强大的@ExtendWith 注解取代。
但是,为了向后兼容,@RunWith 注解仍然可以在 JUnit 5 中使用。
2. 使用基于 JUnit 4 的 Runner 运行测试
我们可以使用@RunWith 注解在任何旧的 JUnit 环境中运行 JUnit 5 测试。
让我们看一个在仅支持 JUnit 4 的 Eclipse 版本中运行测试的示例。
首先,让我们创建我们要测试的类
public class Greetings {
public static String sayHello() {
return "Hello";
}
}
然后我们将创建这个简单的 JUnit 5 测试
public class GreetingsUnitTest {
@Test
void whenCallingSayHello_thenReturnHello() {
assertTrue("Hello".equals(Greetings.sayHello()));
}
}
最后,让我们添加这个注解以便能够运行测试
@RunWith(JUnitPlatform.class)
public class GreetingsUnitTest {
// ...
}
JUnitPlatform 类是一个基于 JUnit 4 的 runner,它允许我们在 JUnit Platform 上运行 JUnit 4 测试。
让我们记住,JUnit 4 不支持 JUnit Platform 的所有功能,因此这个 runner 的功能有限。
如果在 Eclipse 中检查测试结果,我们可以看到使用了 JUnit 4 runner
3. 在 JUnit 5 环境中运行测试
现在让我们在支持 JUnit 5 的 Eclipse 版本中运行相同的测试。在这种情况下,我们不再需要@RunWith 注解,并且可以编写不带 runner 的测试
public class GreetingsUnitTest {
@Test
void whenCallingSayHello_thenReturnHello() {
assertTrue("Hello".equals(Greetings.sayHello()));
}
}
测试结果显示,我们现在正在使用 JUnit 5 runner
4. 从基于 JUnit 4 的 Runner 迁移
现在让我们迁移一个使用基于 JUnit 4 的 runner 的测试到 JUnit 5。
我们将使用 Spring 测试作为示例
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringTestConfiguration.class })
public class GreetingsSpringUnitTest {
// ...
}
如果我们要将此测试迁移到 JUnit 5,我们需要用新的@ExtendWith 替换@RunWith 注解
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { SpringTestConfiguration.class })
public class GreetingsSpringUnitTest {
// ...
}
SpringExtension 类由 Spring 5 提供,并将 Spring TestContext Framework 集成到 JUnit 5 中。@ExtendWith 注解接受实现Extension 接口的任何类。
5. 结论
在这篇简短的文章中,我们介绍了 JUnit 5 框架中使用 JUnit 4 的@RunWith 注解。
支持本文的代码可在 GitHub 上获取。 一旦你以 Baeldung Pro 会员 身份登录,就开始学习并在项目上进行编码。















