相关疑难解决方法(0)

使用profile进行Spring集成测试

在我们的Spring Web应用程序中,我们使用Spring bean配置文件来区分三种场景:开发,集成和生产.我们使用它们连接到不同的数据库或设置其他常量.

使用Spring bean配置文件非常适合更改Web应用程序环境.

我们遇到的问题是我们的集成测试代码需要改变环境.在这些情况下,集成测试会加载Web应用程序的应用程序上下文.这样我们就不必重新定义数据库连接,常量等(应用DRY原则).

我们设置了如下的集成测试.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = ["classpath:applicationContext.xml"])
public class MyTestIT
{
   @Autowired
   @Qualifier("myRemoteURL")  // a value from the web-app's applicationContext.xml
   private String remoteURL;
   ...
 }
Run Code Online (Sandbox Code Playgroud)

我可以使用它在本地运行@ActiveProfiles,但这是硬编码的,导致我们的测试在构建服务器上失败.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = ["classpath:applicationContext.xml"])
@ActiveProfiles("development")
public class MyTestIT
{ ... }
Run Code Online (Sandbox Code Playgroud)

我也试过使用@WebAppConfiguration希望它可能以某种方式spring.profiles.active从Maven 导入属性,但这不起作用.

另外需要注意的是,我们还需要配置代码,以便开发人员可以运行Web应用程序,然后使用IntelliJ的测试运行器(或其他IDE)运行测试.这对于调试集成测试来说要容易得多.

java spring spring-mvc spring-test

20
推荐指数
3
解决办法
3万
查看次数

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

我有一个简单的小“ 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() { …
    Run Code Online (Sandbox Code Playgroud)

java junit spring-data-jpa spring-boot

3
推荐指数
1
解决办法
4194
查看次数