sco*_*eus 7 java spring spring-ldap spring-boot
我正在使用 Spring Data LDAP 从 LDAP 服务器获取用户数据。
我的文件结构如下所示:
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
Run Code Online (Sandbox Code Playgroud)
这是我的测试课:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,Spring Boot 正在加载application.yml和schema.ldif文件,而不是我的测试 YAML 和 LDIF 文件,尽管我的@TestPropertySource注释明确列出了test.yml. 这似乎是由于自动配置所致,为了方便起见,我更愿意使用它。
我希望@TestPropertySource比自动配置具有更高的优先级,但情况似乎并非如此。这是Spring的一个错误,还是我误解了什么?
作为记录,这是我的test.yml文件(它确实指定了test_schema.ldif):
spring:
ldap:
# Embedded Spring LDAP
embedded:
base-dn: dc=test,dc=com
credential:
username: uid=admin
password: secret
ldif: classpath:test_schema.ldif
port: 12345
validation:
enabled: false
Run Code Online (Sandbox Code Playgroud)
我发现 YML 文件不能与@TestPropertySource注释一起使用。解决这个问题的一个干净方法是使用@ActiveProfile。假设您的带有测试属性的 YML 文件被称为
应用程序集成测试.yml
那么你应该使用这样的注释
@ActiveProfile("integration-test")
Run Code Online (Sandbox Code Playgroud)
因此,我可以通过手动指定使用 LDIF 文件所需的属性来解决此问题。这是因为,根据@TestPropertySource 文档,内联属性比属性文件具有更高的首选项。
@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 {
//...
}
Run Code Online (Sandbox Code Playgroud)
然而,这并不是最好的解决方法:如果我需要定义的属性不止两个怎么办?将它们全部列出来是不切实际的。
编辑:
将我的test.yml文件重命名为,application.yml以便它覆盖生产文件,这样就达到了目的。事实证明,该TestPropertySource注释仅适用于 .properties 文件。
| 归档时间: |
|
| 查看次数: |
13177 次 |
| 最近记录: |