SpringBoot整合Junit单元测试(解决空指针异常)

1.依赖

依赖只需要导入Spring-Boot-starter、Spring-Boot-test(不需要另导入junit依赖)

XML 复制代码
  <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-test</artifactId>
     <scope>test</scope>
  </dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
//web里包含starter

2.测试包结构和源码包结构必须相同(踩了很大的坑才发现的!!!)

3. 注解

注意点:

  • 如果要用到Spring容器里的Bean,要在类上加@SpringBootTest注解,不然会报空指针
  • 导的是org.junit.jupiter.api.Test,不是Junit的org.junit.Test
相关推荐
Narutolxy32 分钟前
Python 单元测试:深入理解与实战应用20240919
python·单元测试·log4j
bjzhang7533 分钟前
SpringBoot开发——集成Tess4j实现OCR图像文字识别
spring boot·ocr·tess4j
flying jiang38 分钟前
Spring Boot 入门面试五道题
spring boot
小菜yh39 分钟前
关于Redis
java·数据库·spring boot·redis·spring·缓存
爱上语文2 小时前
Springboot的三层架构
java·开发语言·spring boot·后端·spring
荆州克莱2 小时前
springcloud整合nacos、sentinal、springcloud-gateway,springboot security、oauth2总结
spring boot·spring·spring cloud·css3·技术
serve the people2 小时前
springboot 单独新建一个文件实时写数据,当文件大于100M时按照日期时间做文件名进行归档
java·spring boot·后端
罗政8 小时前
[附源码]超简洁个人博客网站搭建+SpringBoot+Vue前后端分离
vue.js·spring boot·后端
Java小白笔记11 小时前
关于使用Mybatis-Plus 自动填充功能失效问题
spring boot·后端·mybatis
小哇66611 小时前
Spring Boot,在应用程序启动后执行某些 SQL 语句
数据库·spring boot·sql