【发布时间】:2018-02-20 01:09:51
【问题描述】:
鉴于我有以下 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}"。
我的问题是:如何从 Spring Cloud Config 中读取属性 运行单元测试时在应用程序中处理的服务器,观察 我的测试我什至不关心配置所以我不想明确 必须在我的测试中设置一个值才能启动上下文?
【问题讨论】:
-
您使用什么作为构建工具? Gradle 还是 Maven?还有什么?
-
我正在使用 Maven
标签: java spring unit-testing spring-boot