Spring Boot DataJpaTest单元测试恢复为H2而不是mySql

pau*_*sm4 3 java junit spring-data-jpa spring-boot

我有一个简单的小“ hello world” Spring Boot应用程序。它具有单个实体(“ IssueReport”),并且配置为运行mySQL(而不是默认的H2嵌入式数据库)。

该应用程序本身运行良好。我创建了一个mySql数据库和用户,Spring Boot / Hibernate创建了该表,并在运行该应用程序时成功填充并读取了mySQL数据。生活是美好的-mySQL和Spring Boot应用程序本身没有问题。

问:现在如何在单元测试中使用mySQL(而不是嵌入式H2)?

  1. 我创建了另一个单独的mySQL数据库:test2_test_db

  2. 我正在使用Spring Boot 2.0.6; STS 3.9.6上的Eclipse Photon;Ubuntu Linux。

  3. 我创建application-test.propertiessrc/test/resources/

    spring.datasource.url=jdbc:mysql://localhost:3306/test2_test_db
    spring.datasource.username=springuser
    spring.datasource.password=springuser
    spring.jpa.hibernate.ddl-auto=create
    
    Run Code Online (Sandbox Code Playgroud)
  4. 这是整个单元测试:

    package com.hellospring.example;
    
    import static org.assertj.core.api.Assertions.assertThat;
    import java.util.List;
    import javax.transaction.Transactional;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
    import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
    import org.springframework.test.context.ActiveProfiles;
    import org.springframework.test.context.junit4.SpringRunner;
    import com.hellospring.example.entity.IssueReport;
    import com.hellospring.example.repositories.IssueRepository;
    
    @RunWith(SpringRunner.class)
    @ActiveProfiles("test")
    @Transactional
    @DataJpaTest
    public class IssueRepositoryIntegrationTests {
    
         @Autowired
         private TestEntityManager entityManager;
    
         @Autowired
         private IssueRepository issueRepository;
    
         @Test
         public void addNewIssue() {
             System.out.println("addNewIssue()...");  // <-- This prints in the console
             final String email = "test@test.io";
             List<IssueReport> resultSet = issueRepository.findAll();  // <-- We get an exception in here...
         }  
    }
    
    Run Code Online (Sandbox Code Playgroud)
  5. 这是控制台错误:

    2018-10-25 22:20:16.381  INFO 13637 --- [           main] c.v.e.IssueRepositoryIntegrationTests    : The following profiles are active: test
    2018-10-25 22:20:16.405  INFO 13637 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@d554c5f: startup date [Thu Oct 25 22:20:16 PDT 2018]; root of context hierarchy
    2018-10-25 22:20:17.059  INFO 13637 --- [           main] beddedDataSourceBeanFactoryPostProcessor : Replacing 'dataSource' DataSource bean with embedded version
    2018-10-25 22:20:17.060  INFO 13637 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'dataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]] with [Root bean: class [org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration$EmbeddedDataSourceFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
    2018-10-25 22:20:17.308  INFO 13637 --- [           main] o.s.j.d.e.EmbeddedDatabaseFactory        : Starting embedded database: url='jdbc:h2:mem:979b3ce9-604e-4efd-a6d4-79576c3d67e9;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'
    2018-10-25 22:20:17.685  INFO 13637 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
      ...  <= I do *NOT* want H2!  I want mySQL!
    
    2018-10-25 22:20:19.315  WARN 13637 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 42102, SQLState: 42S02
    2018-10-25 22:20:19.316 ERROR 13637 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : Table "ISSUE_REPORT" not found; SQL statement:
      ...  <= Here's the exception from running the test...
    
    Run Code Online (Sandbox Code Playgroud)

问:最简单的更改是什么,因此我可以使用mySQL运行单元测试,就像我可以使用mySQL运行Spring Boot应用程序一样?

问:“ @ DataJpaTest”是这里的最佳选择,还是应该尝试其他注释?

问:我必须创建一个单独的“ Bean”类吗?如果是这样,您能举个例子吗?

================================================== ==============

感谢您的所有答复。包括Simon Martinelli(现已删除)的回复。

解析度:

  1. 我原来的样子application-test.properties还可以。

  2. 我把它放在错误的位置:任何配置文件的所有 application.properties文件通常都应放在同一项目文件夹中:src/main/resources

    <=示例: src/main/resources/application-test.properties

  3. @Transactional在这里无关紧要-我删除了它。我保留了它@ActiveProfiles("test")

  4. 我补充了Per Karthik R的建议@AutoConfigureTestDatabase(replace=Replace.NONE)

  5. 到那时,测试成功读取application-test.properties并使用MySQL代替了H2。

  6. 最终注释:

    @RunWith(SpringRunner.class)
    @ActiveProfiles("test")
    @DataJpaTest
    @AutoConfigureTestDatabase(replace=Replace.NONE)
    public class IssueRepositoryIntegrationTests {
    
    Run Code Online (Sandbox Code Playgroud)

我发现此链接特别有用:Spring Boot –基于配置文件的属性和yaml示例

<=我一直发现http://www.mkyong.com上的所有资料都非常好!

Kar*_*k R 8

默认情况下,@DataJpaTest在内存H2数据库中用于回购测试。如果需要使用实际的数据库,则可以考虑禁用自动配置,也可以考虑在@SpringBootTest启用整个应用程序Web MVC的地方使用。

要禁用自动配置:

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@Transactional
@DataJpaTest
@AutoConfigureTestDatabase(replace=Replace.NONE)
public class IssueRepositoryIntegrationTests 
Run Code Online (Sandbox Code Playgroud)

@AutoConfigureTestDatabase为您配置测试H2 DB。您可以在上面特别提及不使用,也可以将此自动配置排除为:

@EnableAutoConfiguration(exclude=AutoConfigureTestDatabase.class)
Run Code Online (Sandbox Code Playgroud)

PS:我还没有尝试过上述排除方法。

有关更多信息,请访问javadoc: https : //docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/autoconfigure/jdbc/AutoConfigureTestDatabase.html

  • `@AutoConfigureTestDatabase(replace=Replace.NONE)` 对我有用,拯救了我的一天。一整天我都在调试各个角落,搜索了大量资源,但没有找到启用自动配置数据库的原因。这是一个很好的解决方案。 (2认同)