鉴于我有以下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;
}
我希望能够运行以下测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class S2Test {
@Autowired
S2 s;
@Test
public void t2() {
System.out.println(s.s1.i);
}
}
我的问题是,因为我想单独测试S2类,因为它使用@Autowired我必须在我的测试中有一个Spring上下文,但是当Spring上下文启动时它会尝试创建包含bean的所有3个bean与@Value.由于此值仅可从Spring Cloud Config Server获得,因此无法创建上下文,从而产生错误:org.springframework.beans.factory.BeanCreationException:创建名为’serviceConfig’的bean时出错:注入自动连接的依赖项失败;嵌套异常是java.lang.IllegalArgumentException:无法在字符串值“${example.property}”中解析占位符’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?