在使用junit4的注解的时候,获取不到容器rabbitTemplate
报了个空指针异常:java.lang.NullPointerException: Cannot invoke "org.springframework.amqp.rabbit.core.RabbitTemplate.convertAndSend(String, String, Object)" because "this.rabbitTemplate" is null
解决方式一:在测试类上加上@Runwith(SpringRunner.class就可以解决了)
解决方式二:使用junit5的@Test注解
总结:
-
JUnit 4:
- 导入的
@Test
注解是org.junit.Test
。 - 需要在测试类上使用
@RunWith
注解来指定测试运行器,通常使用@RunWith(SpringRunner.class)
来与 Spring 集成。
- 导入的
-
JUnit 5:
- 导入的
@Test
注解是org.junit.jupiter.api.Test
。 - 不需要使用
@RunWith
注解,JUnit 5 引入了自己的扩展模型,不再依赖于运行器。
- 导入的
因此,如果你使用的是 JUnit 4,则需要导入 org.junit.Test
注解并使用 @RunWith(SpringRunner.class)
,而如果你使用的是 JUnit 5,则应导入 org.junit.jupiter.api.Test
注解,不需要 @RunWith
注解。
在你的测试类中使用哪种注解取决于你的项目的测试框架和版本。如果你是在使用 Spring Boot,通常会使用 JUnit 4,并且需要在测试类上添加 @RunWith(SpringRunner.class)
注解。如果你想使用 JUnit 5,你需要适配 Spring Boot 2.2+ 版本,并相应地更新你的测试类和依赖。