![](/img/trans.png)
[英]How to read a variable from a yaml file into the application.properties?
[英]How to read variable from application.properties from method that is testing
我有课:
@Service
public class A {
@Value("${a.b.c}")
private String abc;
public void foo() {
sout(abc);
}
}
我有测试课:
@SpringBootTest
@SpringBootConfiguration
@RunWith(SpringRunner.class)
@TestPropertySource(locations = "classpath:application.yml")
public class TestA {
@Value("${a.b.c}")
private String abc;
@InjectMocks
private A a;
@Test
public void testFoo() {
this.a.foo();
}
}
在调试测试方法testFoo()
,我看到从application.yml
文件读取了变量abc
。 但是,在foo()
方法内部,我看到变量abc
为空。 尝试测试此方法时,如何设置变量abc
以使其在方法foo()
可用?
第一步是回答这个问题:我是在单元测试类中的代码,还是在集成测试Spring和包含类的代码集合的组合?
如果您正在对代码进行单元测试,则不必让Spring做它的事情。 相反,您只需要实例化类,设置Spring会为您设置的值,执行要测试的方法,然后验证方法是否正确执行。
这是按照我的建议重写的示例单元测试:
public class TestA
{
private static final String VALUE_ABC = "VALUE_ABC";
private A classToTest;
@Test
public void testFoo()
{
classToTest.foo();
}
@Before
public void preTestSetup()
{
classToTest = new A();
ReflectionTestUtils.setField(
classToTest,
"abc",
VALUE_ABC)
}
}
一些注意事项:
ReflectionTestUtils
是Spring-test的一部分。 @InjectMocks
因为您没有要注入的@InjectMocks
。 sout
,所以我从测试中排除了它。 您应该验证以正确的值(在本例中为VALUE_ABC)调用了sout方法。 @RunWith
批注。 您可以尝试覆盖这样的属性:
@TestPropertySource(locations = "location.properties",
properties = "a.b.c=123")
从这里取的例子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.