spring boot 跑junit 报错

本文解决了一个Spring Boot应用中使用JUnit进行测试时出现的数据库配置错误问题。作者通过调整测试类上的注解从@ContextConfiguration改为@SpringBootTest成功解决了问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在网上copy一个spring boot junit的实例,想要测试一下Request请求

 

http://blog.youkuaiyun.com/catoop/article/details/50752964

 

将url替换成可用地址后, run as ->  junit test 发现报错了,log如下:

 

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

 

报错的意思是database没有配置好,database type为NONE。但实际上我的spring boot是可以启动,通过浏览器也是可以访问controller获取正确数据的。所以推断肯定是spring boot junit配置有问题。

 

然后又找了下资料发现

 

http://blog.youkuaiyun.com/u014695188/article/details/52262895

 

 

@RunWith(SpringJUnit4ClassRunner.class)  
@SpringBootTest(classes=Application.class)// 指定spring-boot的启动类   
//@SpringApplicationConfiguration(classes = Application.class)// 1.4.0 前版本  
public class SpringBootJdbcTest {  
       

 

 

检查了下我的springboot版本是1.5.3。而junit 里的配置为

 

 

写道
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = Application.class)
public class ControllerTest {

 

 

果断将SpringApplicationConfiguration 和WebAppConfiguration 替换为SpringBootTest

再跑,不再报错,测试通过。

 

再进一步查了下原因发现

 @SpringBootTest 会配置spring boot环境而@ContextConfiguration 只会配置spring环境。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值