【问题标题】:Another datasource for service layer unit testing服务层单元测试的另一个数据源
【发布时间】:2015-03-06 03:55:36
【问题描述】:

在学习了 JUnit 并体验了它对程序员和项目的好处之后,我现在想对每个实体的服务层进行单元测试,并测试每个方法是否正常工作。

到目前为止,我已经为我的所有服务类创建了一个单元测试,但问题是数据源的数据不适合测试。因此,我必须为服务层测试创建另一个数据库,并为服务层的单元测试配置数据源。但事情是我不知道如何配置另一个只有src/test/java 可以访问并且在生产时无法访问的数据源。我对 SpringBoot 和 SpringData 还很陌生,所以我在这里询问如何配置这些要求。

到目前为止,我有这个 application.properties 配置。

spring.datasource.url=<DatabaseURL>
spring.datasource.username=<DatabaseUsername>
spring.datasource.password=<DatabasePassword>
spring.datasource.driver-class-name=<DatabaseDriver>
// another datasource configuration

这是一个服务类的示例代码。其中使用application.properities - dataSource 配置。

@Service
public class FooService {
    @PersistenceContext
    private EntityManager entityManager;

    public List<Foo> findAllByFooForm(FooForm fooForm) {
        // JPA CriteriaBuilder query accroding to FooForm
        return entityManager.createQuery(query).getResultList();
    }
}

最后,这是一个服务类的单元测试示例代码。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class FooServiceTest {
    @AutoWired
    private FooService fooService

    @Test
    public void testFindAllByFooForm() {
        // Test statements
    }
}

【问题讨论】:

    标签: unit-testing junit spring-data spring-boot


    【解决方案1】:

    有几种方法可以结合起来让您很好地控制这一点。

    首先,如果您创建src/test/resources/application.properties,那么它只会在测试期间在类路径中可用。它将覆盖您在src/main/resouces/application.properties 中定义的任何属性。

    如果您使用内存数据库来支持这些测试,那么您可以通过使用以下属性确保加载不同的 import.sql 文件:

    spring.jpa.properties.hibernate.hbm2ddl.import_files=import-test1.sql
    

    该注释采用逗号分隔的导入脚本列表,因此您可以让一个脚本加载一组基本数据,并由其他脚本加载其他(可能是特定于测试的)数据。

    如果您希望在每个测试中连接到不同的数据库,或者使用不同的导入脚本,那么您可以使用配置文件来触发它。如果您创建一个属性文件application-test1.properties,那么测试本身会导致使用注释加载该文件:@ActiveProfiles({"test1"})

    【讨论】:

    • 您的建议非常有效。不幸的是,Eclipse 总是向我显示警告The resource is a duplicate of src/main/resources/application.properties and was not copied to the output folder。虽然这种行为似乎很正常,但是否有另一种方法可以解决这个问题,而无需禁用对 Eclipse 的此类警告?
    • 我不知道...我不在 Eclipse 中进行任何构建。 :)
    猜你喜欢
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    相关资源
    最近更新 更多