2017-10-12 347 views
0

我是新来的春天开机当外部属性文件,我有文件使用@TestPropertySource批注与@SpringBootTest沿装载性能麻烦,这里是我的代码弹簧引导@TestPropertySource不加载使用@SpringBootTest

@RunWith(SpringRunner.class) 
@SpringBootTest() 
@TestPropertySource(locations="classpath:test_application.properties") 
@Sql(value = {"/user_test_script.sql"}) 
@AutoConfigureTestDatabase(replace = Replace.NONE) 
public class UserServiceImpleIntegrationTest { 


    @Autowired 
    private UserService userService; 

    @Autowired 
    ApplicationContext applicationContext; 


    @Test 
    public void testGetAllGuestUsers() throws IOException { 
     List<User> users =userService.getAllGuestUsers(0, 10); 

     assertThat(users).isNotNull(); 
     assertThat(users).isNotEmpty(); 
     assertThat(users).are(new Condition<User>() { 
       public boolean matches(User user) { 
        return user.getFirstName().contains("Guest"); } 
       }); 
    } 
} 

这里是我的test_application.properties文件内容

# Connection url for the database "test" 
spring.datasource.url=jdbc:mysql://localhost:3306/test_db 
spring.datasource.driverClassName=com.mysql.jdbc.Driver 
spring.datasource.username=root 
spring.datasource.password=root 


# Hibernate 
spring.jpa.hibernate.ddl-auto=create-drop 
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect 
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext 
spring.jpa.show-sql = true 
spring.jpa.properties.hibernate.format_sql=true 
spring.datasource.testWhileIdle = true 
spring.datasource.validationQuery = SELECT 1 


#LOGGING 
logging.level.org.hibernate.SQL=DEBUG 
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE 
logging.level.org.springframework.web=ERROR 
logging.level.org.hibernate=DEBUG 

spring.profiles.active=junit 

#TransactionManagement 
logging.level.org.springframework.transaction.interceptor=TRACE 

我的类路径:test_application.properties位于的src /测试/资源的位置。

当我用@DataJpaTest相同@TestPropertySource注释,属性文件加载为excepted.Here是我同

@RunWith(SpringRunner.class) 
@DataJpaTest 
@AutoConfigureTestDatabase(replace = Replace.NONE) 
@Sql(value = {"/item_test_script.sql" ,"/image_test_script.sql"}) 
@TestPropertySource(value="classpath:test_application.properties") 
public class ItemRepoTest { 


    @Autowired 
    ItemRepo itemRepo; 

    @Test 
    public void testGetAllImagesByItemId() { 
     List<Image> images= itemRepo.getAllImagesByItemId(1l); 
     assertThat(images).isNotEmpty(); 
     assertThat(images).size().isGreaterThanOrEqualTo(1); 

    } 

} 

非常奇怪的代码是如果我使用性质属性为

@TestPropertySource(属性= { “spring.datasource.username =根”, “spring.datasource.password =根”})

而不是位置属性,然后这些值被用来加载数据库。我在这里丢失了什么,或者什么配置是错误的。

回答

1

我在我的测试配置类代替@TestConfiguration注释之一@Configuration,所以application.properties文件被加载并更换test_application.properties文件

+0

很高兴,你解决了它。 – Amiko

1

尝试从注释中移除classpath,应该看起来像这样。 @TestPropertySource("test_application.properties")

@TestPropertySource通常配合使用@ContextConfiguration