假设我有以下 3 个 Bean:
@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;
}
我希望能够运行以下测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class S2Test {
@Autowired
S2 s;
@Test
public void t2() {
System.out.println(s.s1.i);
}
}
我遇到的问题是因为我想测试 S2
隔离类,因为它使用 @Autowired
我的测试中必须有一个 Spring 上下文,但是当 Spring 上下文启动时,它会尝试创建所有 3 个 bean,其中包括带有 @Value
的 bean。 .由于此值仅可从 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}"
.
My Question is: How are properties read from Spring Cloud Config Server handled in the application when unit tests are run, observe in my test i dont even care about the config so I dont want to explicitly have to set a value in my test just for the context to be started?
最佳答案
我建议简单地在“src/test/resources/application.properties”中将“spring.cloud.config.enabled”添加为 false,并为“example.property”添加一个测试值。
spring.cloud.config.enabled=false
example.property=testvalue
这很简单,不会影响您的代码库。 如果需要,您还可以使用 MOCK Web 环境和不包含这些 bean 的自定义测试应用程序配置。
@SpringBootTest(classes = TestOnlyApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
关于java - 从 Spring boot 单元测试中排除 Spring Cloud Config Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46161683/