JUnit之@RunWith注解


首先要强调的是:

  • 在JUnit5中,@RunWith注释已由功能更强大的@ExtendWith注释替换。
  • 但是,为了向后兼容,@RunWith批注仍可以在JUnit5中使用。

@RunWith的使用

例子:

创建要测试的类:

public class Greetings {
    public static String sayHello() {
        return"Hello";
    }  
}

进行JUnit5测试:

@RunWith(JUnitPlatform.class)
public class GreetingsTest {
    @Test
    void whenCallingSayHello_thenReturnHello() {
        assertTrue("Hello".equals(Greetings.sayHello()));
    }
}

有两点要注意:

  • JUnitPlatform类是一个基于JUnit4的运行器,它使我们可以在JUnit5平台上运行JUnit4测试。
  • 但是JUnit4不支持新的JUnit Platform的所有机制,因此该运行器的功能有限。

在JUnit5环境中测试

例子:

不再需要@RunWith注释:

public class GreetingsTest {
    @Test
    void whenCallingSayHello_thenReturnHello() {
        assertTrue("Hello".equals(Greetings.sayHello()));
    }
}

从基于JUnit4的运行器迁移

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

例子:

JUnit4:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringTestConfiguration.class })
public class GreetingsSpringTest {
    // ...
}

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

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { SpringTestConfiguration.class })
public class GreetingsSpringTest {
    // ...
}

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