JUnit5 @RunWith

JUnit5 @RunWith

1.简介

在这篇快速文章中,我们将介绍JUnit 5框架中@RunWith注释的用法。

在JUnit 5中,@ RunWith注释已由功能更强大的@ExtendWith注释替换。

但是,为了向后兼容,@ RunWith批注仍可以在JUnit5中使用。

2.使用基于JUnit4的运行器运行测试

我们可以使用@RunWith批注在任何其他较旧的JUnit环境中运行JUnit5测试。

让我们看一个在仅支持JUnit4的Eclipse版本中运行这些测试的示例。

首先,让我们创建要测试的类:

1
2
3
4
5
public class Greetings {
    public static String sayHello() {
        return"Hello";
    }  
}

接下来,让我们创建这个简单的JUnit5测试:

1
2
3
4
5
6
public class GreetingsTest {
    @Test
    void whenCallingSayHello_thenReturnHello() {
        assertTrue("Hello".equals(Greetings.sayHello()));
    }
}

最后,让我们添加此批注以能够运行测试:

1
2
3
4
@RunWith(JUnitPlatform.class)
public class GreetingsTest {
    // ...
}

JUnitPlatform类是一个基于JUnit4的运行器,它使我们可以在JUnit平台上运行JUnit4测试。

让我们记住,JUnit4不支持新的JUnit Platform的所有功能,因此该运行器的功能有限。

如果我们在Eclipse中检查测试结果,可以看到使用了JUnit4运行程序:

junit4 test

3.在JUnit5环境中运行测试

现在,让我们在支持JUnit5的Eclipse版本中运行相同的测试。在这种情况下,我们不再需要@RunWith注释,并且可以在没有运行程序的情况下编写测试:

1
2
3
4
5
6
public class GreetingsTest {
    @Test
    void whenCallingSayHello_thenReturnHello() {
        assertTrue("Hello".equals(Greetings.sayHello()));
    }
}

测试结果表明,我们现在正在使用JUnit5运行程序:

junit5 test

4.从基于JUnit4的运行器迁移

现在,让我们将使用基于JUnit4的运行器的测试迁移到JUnit5。

我们将以Spring测试为例:

1
2
3
4
5
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringTestConfiguration.class })
public class GreetingsSpringTest {
    // ...
}

如果要将此测试迁移到JUnit5,则需要用新的@ExtendWith替换@RunWith批注:

1
2
3
4
5
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { SpringTestConfiguration.class })
public class GreetingsSpringTest {
    // ...
}

SpringExtension类由Spring 5提供,并将Spring TestContext Framework集成到JUnit 5中。@ExtendWith注释接受任何实现Extension接口的类。

5.结论

在这篇简短的文章中,我们介绍了在JUnit5框架中使用JUnit 4的@RunWith批注。

示例的完整源代码可在GitHub上获得。