![](/img/trans.png)
[英]Spring-boot - Parameterized Test - Access Application.properties in MethodSource
[英]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.