tow*_*ity 5 java junit mockito spring-boot context-configuration
有一个@Value注释的常量,在运行测试时没有被初始化,当构造函数中需要它时,它会抛出NullPointerException。
要测试的示例类:
class TestClass {
@Value("${test.value1}")
private String value1;
private final TestTemplate testTemplate;
public TestClass(TestTemplateBuilder builder) {
testTemplate = builder.someMethod(value1).build();
}
---
}
Run Code Online (Sandbox Code Playgroud)
测试类示例:
@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());
}
---
}
Run Code Online (Sandbox Code Playgroud)
尝试了一些方法,但没有任何效果:
application.properties具有所需值的文件。application-test.properties并添加@TestPropertySource(locations="classpath:application-test.properties").@SpringBootTest(properties = { "test.value1=VALUE" })我也尝试过其他一些东西,但我得到的NullPoiterException是someMethod(value1).
版本:
| 归档时间: |
|
| 查看次数: |
7720 次 |
| 最近记录: |