有一个@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
具有所需值的文件。
- Created
application-test.properties
并添加了@TestPropertySource(locations="classpath:application-test.properties")
.
@SpringBootTest(properties = { "test.value1=VALUE" })
我也尝试过其他一些东西,但我得到的是NullPoiterException
at someMethod(value1)
.
版本:
- 爪哇:1.8
- 春季启动:2.1.17
- 朱尼特:4.12
- 莫基托:2.23.4
如果 @Before 不起作用,请尝试使用 @BeforeEach。这对我有用。
`@BeforeEach
public void setUp() {
ReflectionTestUtils.setField(yourInstanceClass, "fieldName", "fieldValue");
}`
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)