首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring Boot在集成测试中的数据源自动配置问题

Spring Boot在集成测试中的数据源自动配置问题
EN

Stack Overflow用户
提问于 2018-02-24 21:31:24
回答 2查看 2K关注 0票数 3

我尝试从application.properties更改为application.yml。我的Spring Boot应用程序启动并正常工作,但是所有集成测试用例都失败了。

这是控制台日志中的错误消息

代码语言:javascript
复制
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v1.5.10.RELEASE)

***************************
APPLICATION FAILED TO START
***************************

 Description:

Field datasource in com.example.core.config.ServiceConfig 
required a bean of type 'javax.sql.DataSource' that could not be found.

Action:

Consider defining a bean of type 'javax.sql.DataSource' in your configuration.

尽管我在application.yml文件中定义了数据源,并且它在运行Spring boot app时运行良好……但在运行测试用例时会失败,无论是通过Gradle runner还是通过Gradle -build任务。

以下是我的配置:

代码语言:javascript
复制
spring:
  profiles: default
  datasource:
    hikari:
          minimum-idle: 1
          maximum-pool-size: 5
          pool-name: yourPoolName
          auto-commit: false
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://xxx
    username: xxx
    password: xxx
    maximumPoolSize: 5
    type: com.zaxxer.hikari.HikariDataSource

---
spring:
  profiles: dev
  datasource:
    hikari:
          minimum-idle: 1
          maximum-pool-size: 5
          pool-name: yourPoolName
          auto-commit: false
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://xxx
    username: xx
    password: xx
    maximumPoolSize: 5
    type: com.zaxxer.hikari.HikariDataSource

在我的测试类中,我尝试了所有方法:

代码语言:javascript
复制
@SpringBootTest also 
@ContextConfiguration(classes = {ServiceConfig.class, ApplicationConfig.class},initializers = ConfigFileApplicationContextInitializer.class)

似乎没有任何帮助..运行测试似乎完全忽略了aapplication.yml

applicationConfig

代码语言:javascript
复制
@Configuration
public class ApplicationConfig {

    /**
     *  Total customization - see below for explanation.
     */
    @Autowired
    private Environment environment;

    @PostConstruct
    private void inti () {
       String [] ps =  this.environment.getActiveProfiles();
        for (String p : ps) {

            System.out.println("Currrent profile is "+p);
        }
    }


    @Autowired
    DataSource datasource;

    @Bean
    public DataSourceTransactionManager transactionManager() throws SQLException {
        return new DataSourceTransactionManager(datasource);
    }
    @Bean
    public SqlSessionFactory mySqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(datasource);
        return sessionFactory.getObject();
    }

下面是我的一个测试类:

代码语言:javascript
复制
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {  ApplicationConfig.class})
@ActiveProfiles("dev")
public class OrdersServiceTest {


    @Autowired
    OXUserDetailsService ous;

    @Autowired
    OXOrderServices ors;


    @Before
    public void setup() throws Exception {

    }


    @Test
    public void testgetMyOrders() {
        OXUser ou = ous.getUserById(1);

        OXCustomer c = ors.showOrderForUser(ou);
        Assert.assertNotNull(c);
    }

    @Test
    public void testgetOrderItemsByOrderId() {
        List<OXOrderItem> ous =ors.getOrderItemsByOrderId(1);
        Assert.assertNotNull(ous);
    } }

我使用的spring版本是5.0.4,以下是相对的引导依赖关系:

代码语言:javascript
复制
dependencies {
...
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.1')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile group: 'org.hamcrest', name: 'hamcrest-library', version:'1.3'
    testCompile group: 'com.jayway.jsonpath', name: 'json-path', version:'2.2.0'
    testCompile 'org.yaml:snakeyaml:1.19'
}

我是不是遗漏了一些spring boot的魔法配置?为什么它在测试用例上失败了?

EN

回答 2

Stack Overflow用户

发布于 2018-02-24 22:08:59

(1)文件application.yml,添加以下行

代码语言:javascript
复制
spring:
  profiles: test
  datasource:
    hikari:
          minimum-idle: 1
          maximum-pool-size: 5
          pool-name: yourPoolName
          auto-commit: false
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://xxx
    username: xxx
    password: xxx
    maximumPoolSize: 5
    type: com.zaxxer.hikari.HikariDataSource

通过解开profiles: test线路,Spring Boot被自动配置用于测试。

(2)文件OrdersServiceTest.java

代码语言:javascript
复制
import org.junit.Assert;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class OrdersServiceTest {

    @Autowired
    OXUserDetailsService ous;

    @Autowired
    OXOrderServices ors;

    @Before
    public void setup() throws Exception {

    }

    @Test
    public void testgetMyOrders() {
        OXUser ou = ous.getUserById(1);
        OXCustomer c = ors.showOrderForUser(ou);
        Assert.assertNotNull(c);
    }

    @Test
    public void testgetOrderItemsByOrderId() {
        List<OXOrderItem> ous = ors.getOrderItemsByOrderId(1);
        Assert.assertNotNull(ous);
    }

}

参考:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing (支持测试的自动配置)

票数 0
EN

Stack Overflow用户

发布于 2018-02-25 11:45:59

你可能在yml文件中有额外的空格,

代码语言:javascript
复制
spring:
  profiles: test
  datasource:
    hikari:
          minimum-idle: 1
          maximum-pool-size: 5
          pool-name: yourPoolName
          auto-commit: false

相反,这会起作用吗?

代码语言:javascript
复制
spring:
  profiles: test
  datasource:
    hikari:
      minimum-idle: 1
      maximum-pool-size: 5
      pool-name: yourPoolName
      auto-commit: false
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48963408

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档