写在最前面:
本篇文章能解决的问题:springboot项目从入口类启动失败;测试类无法测试;报错提示
无法找到bean注入等等。。这些错误多半是由于项目结构错误,依赖没引好,注解放错原因导致的。
本文将持续更新。。
test类和springboot启动类结构
注意:springboot程序入口类和test类在同一包结构底下:com.huang
关于springboot启动类
启动类要放在 com.huang的这种package下面,不可以直接放在java包底下,不然启动报错。
另:@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})这个注解是让启动时允许不连接DB
@SpringBootApplication
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class RabbitMQAPP {
public static void main(String[] args) {
SpringApplication.run(RabbitMQAPP.class,args);
}
}
关于测试类
springboot项目测试类所需maven依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
测试类要点总结:
- 测试类的所需的pom依赖直接照抄
- 测试类注解如下代码快所示:注意注解写法: SpringBootTest (classes = RabbitMQAPP.class) class是springboot启动类的class!!
- test包的结构一定要和springboot启动类的结构一样:都要有com.huang
@SpringBootTest(classes = RabbitMQAPP.class)
@RunWith(SpringRunner.class)
@Slf4j
public class PractiseTest {
@Autowired
private Publisher publisher;
@Test
public void testSpringEvent(){
publisher.sendMsg();
}
}