Java Spring启动测试:@TestPropertySource未覆盖@EnableAutoConfiguration
我使用SpringDataLDAP从LDAP服务器获取用户数据 我的文件结构如下所示:Java Spring启动测试:@TestPropertySource未覆盖@EnableAutoConfiguration,java,spring,spring-boot,spring-ldap,Java,Spring,Spring Boot,Spring Ldap,我使用SpringDataLDAP从LDAP服务器获取用户数据 我的文件结构如下所示: main java com.test.ldap Application.java Person.java PersonRepository.java resources application.yml schema.ldif test java Tests.java resources test.yml te
main
java
com.test.ldap
Application.java
Person.java
PersonRepository.java
resources
application.yml
schema.ldif
test
java
Tests.java
resources
test.yml
test_schema.ldif
这是我的测试课:
import com.test.ldap.Person;
import com.test.ldap.PersonRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {PersonRepository.class})
@TestPropertySource(locations = "classpath:test.yml")
@EnableAutoConfiguration
public class Tests {
@Autowired
private PersonRepository personRepository;
@Test
public void testGetPersonByLastName() {
List<Person> names = personRepository.getPersonNamesByLastName("Bachman");
assert(names.size() > 0);
}
}
因此,我可以通过手动指定使用LDIF文件所需的属性来解决这个问题。这是因为,根据文档,内联属性比属性文件具有更高的首选项
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {PersonRepository.class})
@TestPropertySource(properties =
{"spring.ldap.embedded.ldif=test_schema.ldif", "spring.ldap.embedded.base-dn=dc=test,dc=com"})
@EnableAutoConfiguration
public class Tests {
//...
}
然而,这并不是最好的解决方法:如果我需要定义的属性不止两个,该怎么办?把它们都列在那里是不切实际的
编辑:
将我的
test.yml
文件重命名为application.yml
,这样就可以覆盖生产文件。事实证明,TestPropertySource
注释只适用于.properties文件。我发现YML文件不适用于@TestPropertySource注释。
一个简单的解决方法是使用@ActiveProfile。假设调用了具有测试属性的YML文件
application-integration-test.yml
那么您应该像这样使用注释
@ActiveProfile("integration-test")
您不能使用
@(测试)PropertySource
加载.yml
文件,它只适用于.properties
文件。]这…似乎不是事实,请参阅对我答案的编辑是的。您重命名它的事实使它由默认的Spring引导加载机制加载,而不是通过@TestPropertySource
。如果删除@TestPropertySource
,它仍然可以工作。似乎将我的test.yml文件重命名为applications.yml会影响到另一个YAML文件,而不管是否存在@TestPropertySource注释。可以确认YAML文件不能与TestPropertySource一起使用!!
@ActiveProfile("integration-test")