[英]How to read variable from application.properties from method that is testing
I have class: 我有课:
@Service
public class A {
@Value("${a.b.c}")
private String abc;
public void foo() {
sout(abc);
}
}
I Have test class: 我有测试课:
@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();
}
}
When I debugging the test method testFoo()
, I see that variable abc
is read from the application.yml
file. 在调试测试方法testFoo()
,我看到从application.yml
文件读取了变量abc
。 But, inside the foo()
method, I see that the variable abc
is null. 但是,在foo()
方法内部,我看到变量abc
为空。 How can I set variable abc
such that it is available in method foo()
when I trying to test this method? 尝试测试此方法时,如何设置变量abc
以使其在方法foo()
可用?
Step one is to answer this question: Am I unit testing the code in my class or am I integration testing the combination of Spring and some collection of code that includes my class? 第一步是回答这个问题:我是在单元测试类中的代码,还是在集成测试Spring和包含类的代码集合的组合?
If you are unit testing your code, then it is not necessary to have Spring do its thing. 如果您正在对代码进行单元测试,则不必让Spring做它的事情。 Instead, you only need to instantiate your class, set the values that Spring would have set for you, execute the method you are testing, then verify that your method executed correctly. 相反,您只需要实例化类,设置Spring会为您设置的值,执行要测试的方法,然后验证方法是否正确执行。
Here is your example unit test rewritten as I suggested: 这是按照我的建议重写的示例单元测试:
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)
}
}
Some Notes: 一些注意事项:
ReflectionTestUtils
is part of Spring-test. ReflectionTestUtils
是Spring-test的一部分。 @InjectMocks
because you have no mocks to inject. 您不需要使用@InjectMocks
因为您没有要注入的@InjectMocks
。 sout
is, so I excluded it from the test. 我不知道什么是sout
,所以我从测试中排除了它。 You should verify that the sout method was called with the correct value (in this case VALUE_ABC). 您应该验证以正确的值(在本例中为VALUE_ABC)调用了sout方法。 @RunWith
annotation. 如果您只是对代码进行单元测试,则不需要Spring,这意味着您不需要使用@RunWith
批注。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.