Spring MVC 控制器单元测试:如何设置私有实例布尔字段?

Spring MVC Controller Unit Testing : How do I set private instance boolean field?

我有一个 Spring MVC REST 控制器 class,它有一个通过 @Value 注入的私有实例布尔字段,

@Value("${...property_name..}")
private boolean isFileIndex;

现在要对这个控制器进行单元测试 class,我需要注入这个布尔值。

如何使用 MockMvc 做到这一点?

我可以使用反射,但 MockMvc 实例没有给我传递给 Field.setBoolean() 方法的底层控制器实例。

测试 class 在不模拟或注入此依赖项的情况下运行,其值始终为 false。我需要将它设置为 true 以覆盖所有路径。

设置如下所示。

@RunWith(SpringRunner.class)
@WebMvcTest(value=Controller.class,secure=false)
public class IndexControllerTest {

    @Autowired
    private MockMvc mockMvc;
 ....
}

我的首选是在构造函数中设置它并用 @Value 注释构造函数参数。然后你可以在测试中传递你想要的任何东西。

this answer

您可以使用@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);

        //..
    }

}