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

时间:2018-02-24 13:31:24

标签: java spring spring-boot yaml integration-testing

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

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

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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启动应用程序时工作正常...但在运行测试用例时失败,无论是通过intelliJ runner还是通过Gradle -build任务。

这是我的配置:

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

在我的测试课中我尝试了一切:

@SpringBootTest also 
@ContextConfiguration(classes = {ServiceConfig.class, ApplicationConfig.class},initializers = ConfigFileApplicationContextInitializer.class)
似乎没什么帮助.. 运行测试似乎完全忽略了aapplication.yml

applicationConfig

@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();
    }

这是我的一个测试类:

@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);
    } }
我使用的弹簧版本是5.0.4及以下是相对启动依赖项:

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'
}
我错过了一些春季启动魔法配置吗?为什么它在测试用例上失败了?

2 个答案:

答案 0 :(得分:0)

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

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

通过delcaring行profiles: test,Spring Boot是自动配置进行测试。

(2)档案OrdersServiceTest.java

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(支持测试的自动配置)

答案 1 :(得分:0)

yml文件中可能有多余的空格,

spring:
  profiles: test
  datasource:
    hikari:
          minimum-idle: 1
          maximum-pool-size: 5
          pool-name: yourPoolName
          auto-commit: false

这会改变吗?

spring:
  profiles: test
  datasource:
    hikari:
      minimum-idle: 1
      maximum-pool-size: 5
      pool-name: yourPoolName
      auto-commit: false