繁体   English   中英

使用单独的application.properties创建Spring Boot测试

[英]Create Spring Boot test with separate application.properties

我正在使用Spring Boot开发Web应用程序,现在我正在尝试为DAO层创建测试,并且我想使用不同的配置,该配置将读取自定义属性文件,而不是标准的属性文件。 但是Iam遇到了麻烦,它总是读取默认应用程序。 和hibernate.properties。
想要这样做以具有不同的hibernate.ddl-auto属性进行测试。 但是,当我运行测试时,我看到Spring从资源文件夹中的hibernate.properties读取属性(我故意在该文件中打错字,以便获取Spring读取的异常)。 但是,即使我使用@TestPropertySource ,为什么也要读取该文件呢?
我看到有一些我不知道的东西,但是呢? 包src / test / java / com.guard / dao

@RunWith(SpringRunner.class)
@DataJpaTest
@Rollback

public class LifeguardDaoTest {
    @Autowired
    private LifeguardDao lgDao;

    @Test
    public void selectTest(){
        for (Lifeguard lg :lgDao.getAll()) {
            System.out.println(lg);
        }
    }
}`

测试配置类用于设置上下文包src / test / java / com.guard

@SpringBootApplication
@EntityScan(value = {"com.guard.dao","com.guard.model"})
@TestPropertySource(value = {"classpath:application-test.properties", "classpath:hibernate-test.properties"})
public class TestConfiguration {
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(TestConfiguration.class, args);
        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        System.out.println("Spring boot test generated " + beanNames.length + " beans");

    }
}

必需的application-test.properties和hibernate-test.properties在src / test / java路径上
这是项目结构(抱歉,不知道如何设计)

|src
|--main
|----java
|------com.guard
|----------configuration
|-------------GuardApplication.class (@SpringBootApplication,requires default props)
|--test
|----java
|------application-test.properties
|-------hibernate-test.properties
|-----com.guard
|-------TestConfiguration.class
|-------dao
|---------LifeguardDaoTest.class

我的应用程序test.properties

spring.jpa.properties.hibernate.use_sql_comments=true

spring.jpa.hibernate.dialect=org.hibernate.dialect.HSQLDialect
spring.jpa.hibernate.show_sql=false
spring.jpa.hibernate.format_sql=true
spring.jpa.hibernate.hbm2ddl-auto=create

# even in case if it won`t use "spring.jpa" prefix
hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.show_sql=true
hibernate.format_sql=true

`

在测试目录中创建新的资源目录,并将测试属性文件放在此处。 还将属性文件重命名为application.properties和hibernate.properties

春季测试将从test / resources /目录获取属性。 在这种方法中,您不需要@TestPropertySource

通常,@ TestPropertySource与@ContextConfiguration结合使用。

尝试使用此配置类。

@Configuration
@ComponentScan
@Profile("test")
public class TestConfiguration {

}

和注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@ContextConfiguration(classes = TestConfiguration.class)
@ActiveProfiles("test")
@TestPropertySource(locations="classpath:application-test.properties")
public @interface IntegrationTest { }

然后,您只需像这样编写测试:

@RunWith(SpringJUnit4ClassRunner.class)
@IntegrationTest
public class SomeDaoTest {
...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM