use*_*545 5 java spring unit-testing spring-boot
鉴于我有以下3豆:
@Component
public class ServiceConfig {
// This value is only available from the Spring Cloud Config Server
@Value("${example.property}")
private String exampleProperty;
public String getExampleProperty() {
return exampleProperty;
}
}
@Component
public class S1 {
int i = 1;
}
@Component
public class S2 {
@Autowired
S1 s1;
}
Run Code Online (Sandbox Code Playgroud)
我希望能够运行以下测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class S2Test {
@Autowired
S2 s;
@Test
public void t2() {
System.out.println(s.s1.i);
}
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,因为我想要单独测试S2该类,因为它使用@Autowired我必须在我的测试中有一个Spring上下文,但是当Spring上下文启动时,它会尝试创建包含bean的所有3个bean @Value.由于此值仅可从Spring Cloud Config Server获得,因此将无法创建上下文,从而产生错误:org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'serviceConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'example.property' in string value "${example.property}".
我的问题是:在运行单元测试时,如何在应用程序中处理Spring Cloud Config Server中的属性,在我的测试中观察我甚至不关心配置,所以我不想明确地在我的测试中设置一个值只是为了要开始的背景?
Pyt*_*try 10
我建议只需在"src/test/resources/application.properties"中将"spring.cloud.config.enabled"添加为false,并为"example.property"添加测试值.
spring.cloud.config.enabled=false
example.property=testvalue
Run Code Online (Sandbox Code Playgroud)
这很简单,不会影响您的代码库.如果需要,您还可以使用MOCK Web环境,以及不包含这些bean的自定义测试应用程序配置.
@SpringBootTest(classes = TestOnlyApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
Run Code Online (Sandbox Code Playgroud)
有一些选择。
您可以创建测试配置文件。然后,您将需要创建application-test.yml或application-test.properties归档。在那里,您可以为 设置相同的值example.property。在那里,如果您想使用test配置文件开始一些测试,您可以添加到您的测试类@ActiveProfiles("test")注释中。对于这些测试,test将开始。
您可以example.property通过键入来设置默认值@Value("${example.property:SomeDefaultValue}")。SomeDefaultValue如果未找到属性,将插入。
我建议第一种方法。您可以使用注释设置正确的配置文件,然后您将确定哪个配置文件配置服务器将发送给您。
| 归档时间: |
|
| 查看次数: |
5217 次 |
| 最近记录: |