在单元测试中,@Runwith(SpringRunner.class)和@SpringBootTest有什么不同?
你能给我解释一下每种方法的用例吗?
发布于 2019-11-17 23:28:52
@RunWith(SpringRunner.class) :你需要这个注解来启用像@Autowire,@MockBean等的spring boot特性。在junit测试期间
用于在Spring Boot测试特性和JUnit之间架起一座桥梁。每当我们在JUnit测试中使用任何Spring Boot测试特性时,都需要这个注释。
@SpringBootTest :此注释用于加载完整的应用程序上下文,以进行端到端集成测试
当我们需要引导整个容器时,可以使用@SpringBootTest注释。注释通过创建将在我们的测试中使用的ApplicationContext来工作。
这篇文章提供了关于这两种场景的清晰示例Baeldung
发布于 2020-04-15 14:02:44
@RunWith是JUnit 4中的一个旧注释,用于使用测试运行器。如果您使用的是JUnit 5 (Jupiter),则应该使用@ExtendWith来使用JUnit扩展
“如果您使用的是SpringBootTest 4,不要忘了在测试中添加@RunWith(SpringRunner.class),否则注释将被忽略。如果您使用的是JUnit 5,则不需要添加等效的@ExtendWith(SpringExtension.class)作为@SpringBootTest,并且其他@…测试注释已经使用它进行了注释。
发布于 2019-11-17 23:26:46
来自spring.io:
@RunWith(SpringRunner.class)告诉JUnit使用Spring的测试支持来运行。SpringRunner是SpringJUnit4ClassRunner的新名称,它只是看起来更简单一点。
@SpringBootTest说“bootstrap with Spring Boot‘s support”(例如,加载application.properties并给我所有Spring Boot的好处)
因此,如果您的集成测试不需要Spring Boot加载的所有内容,那么您可能不需要@SpringBootTest
https://stackoverflow.com/questions/58901288
复制相似问题