我有一个 Spring MVC REST Controller 类,它有一个通过 @Value 注入(inject)的私有(private)实例 boolean 字段,
@Value("${...property_name..}")
private boolean isFileIndex;
现在要对这个 Controller 类进行单元测试,我需要注入(inject)这个 boolean 值。
如何使用 MockMvc
做到这一点?
我可以使用反射,但 MockMvc
实例没有提供底层 Controller 实例来传递给 Field.setBoolean()
方法。
测试类运行时无需模拟或注入(inject)此依赖项,其值始终为false
。我需要将其设置为 true
以覆盖所有路径。
设置如下所示。
@RunWith(SpringRunner.class)
@WebMvcTest(value=Controller.class,secure=false)
public class IndexControllerTest {
@Autowired
private MockMvc mockMvc;
....
}
最佳答案
您可以使用@TestPropertySource
@TestPropertySource(properties = {
"...property_name..=testValue",
})
@RunWith(SpringRunner.class)
@WebMvcTest(value=Controller.class,secure=false)
public class IndexControllerTest {
@Autowired
private MockMvc mockMvc;
}
您还可以从文件中加载测试属性
@TestPropertySource(locations = "classpath:test.properties")
<小时/>
编辑:其他一些可能的替代方案
@RunWith(SpringRunner.class)
@WebMvcTest(value=Controller.class,secure=false)
public class IndexControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private Controller controllerUnderTheTest;
@Test
public void test(){
ReflectionTestUtils.setField(controllerUnderTheTest, "isFileIndex", Boolean.TRUE);
//..
}
}
关于java - Spring MVC Controller 单元测试: How do I set private instance boolean field?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44517648/