【发布时间】:2018-08-07 16:12:04
【问题描述】:
使用 Spring Boot 2.0.0.RC2。
我写了一个配置类:
@Configuration
@ConditionalOnProperty("launchdarkly.sdkKey")
public class LDClientConfiguration {
@Bean
public LDClientInterface ldClient(LDClientConfigurationProperties props) {
return new LDClient(props.getSdkKey(), props.getLDConfig());
}
}
还有一个 ConfigurationProperties 类:
@Component
@ConfigurationProperties(prefix = "launchdarkly")
public class LDClientConfigurationProperties {
private String sdkKey;
// more attributes
public void setSdkKey(String sdkKey) {
this.sdkKey = sdkKey;
}
// more setters
public LDConfig getLDConfig() {
LDConfig.Builder builder = new LDConfig.Builder();
// set builder w/ attributes
return builder.build();
}
}
我正在尝试对此进行测试,从 src/test/resources/application-test.yml 读取配置:
launchdarkly:
sdkKey: <redacted>
我有以下依赖项:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-engine</artifactId>
<version>${junit-platform.version}</version>
<scope>test</scope>
</dependency>
并且 junit-platform-surefire-provider 配置在 maven-surefire-plugin v2.19.1
我似乎无法为我的测试类找出正确的注释来从 src/test/resources/application-test.yml 读取配置。
我已经阅读了https://junit.org/junit5/docs/current/user-guide,但似乎仍然无法正确获得注释。任何帮助将不胜感激。
编辑:测试类
@SpringJUnitConfig(SpringBootContextLoader.class)
public class LDClientConfigurationPropertiesTest {
@Autowired
private LDClientConfigurationProperties props;
@Test
public void test() {
LDConfig config = props.getLDConfig();
assertThat(config, notNullValue());
}
}
如果我用 @ExtendWith(SpringExtension.class) 注释类
和@SpringBootTest 然后它尝试加载com/company/spring/launchdarkly/LDClientConfigurationTest-context.xml 然后com/company/spring/launchdarkly/LDClientConfigurationTestContext.groovy 但不寻找yml 文件。
【问题讨论】:
-
你的测试课是什么样子的?
-
测试类添加到帖子^
-
如果您的最终目标只是从特定于测试上下文的属性文件中加载测试属性,那么 Spring Boot 提供了一个简单的配置文件机制:docs.spring.io/spring-boot/docs/current/reference/html/…跨度>
-
是的,这正是我想要做的,但无法让它发挥作用。它不断尝试将文件读取为 XML 而不是 .properties 或 .yml。我已将snakeyaml 添加到测试类路径中。
-
嗯,至少在您发布的代码中,您在
LDClientConfiguration.ldClient()中调用的getSdkKey()getter 不存在。您只是在这里省略了它还是在您的实际代码中也没有它?
标签: java spring maven spring-boot junit5