有一个@Value注解的常量,在运行测试时没有被初始化,当在构造函数中需要它时它会抛出NullPointerException。
要测试的样本类:
class TestClass {
@Value("${test.value1}")
private String value1;
private final TestTemplate testTemplate;
public TestClass(TestTemplateBuilder builder) {
testTemplate = builder.someMethod(value1).build();
}
---
}
示例测试类:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = TestClass.class)
@SpringBootTest
class TestClassTest {
@MockBean
TestTemplateBuilder builder;
@Autowired
TestClass testClass = new TestClass(testTemplate);
@Before
public void setUp() {
ReflectionTestUtils.setField(testClass, "value1", "VALUE");
Mockito.when(builder.build()).thenReturn(new TestTemplate());
}
---
}
尝试过,但没有任何效果:
- 我已创建具有所需值的
application.properties
文件。 - 创建了
application-test.properties
并添加了@TestPropertySource(locations="classpath:application-test.properties")
。 @SpringBootTest(properties = { "test.value1=VALUE"})
我也尝试了一些其他的东西,但我得到的是 someMethod(value1)
处的 NullPoiterException
。
版本:
- Java:1.8
- Springboot:2.1.17
- 6月:4.12
- 模拟:2.23.4
最佳答案
如果@Before 不起作用,请尝试使用@BeforeEach。它对我有用。
`@BeforeEach
public void setUp() {
ReflectionTestUtils.setField(yourInstanceClass, "fieldName", "fieldValue");
}`
关于java - Junit - Spring 启动 : @Value is always null while testing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70602545/