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

Sab*_*han 4 java unit-testing spring-mvc spring-restcontroller

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

@Value("${...property_name..}")
private boolean isFileIndex;
Run Code Online (Sandbox Code Playgroud)

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

我该如何做到这一点MockMvc?

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

测试类运行时无需模拟或注入此依赖项,其值始终为false。我需要将其设置true为覆盖所有路径。

设置如下所示。

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

    @Autowired
    private MockMvc mockMvc;
 ....
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*vic 5

您可以使用@TestPropertySource

@TestPropertySource(properties = {
    "...property_name..=testValue",
})
@RunWith(SpringRunner.class)
@WebMvcTest(value=Controller.class,secure=false)
public class IndexControllerTest {

    @Autowired
    private MockMvc mockMvc;

}
Run Code Online (Sandbox Code Playgroud)

您还可以从文件中加载测试属性

@TestPropertySource(locations = "classpath:test.properties")
Run Code Online (Sandbox Code Playgroud)

编辑:其他一些可能的替代方案

@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);

        //..
    }

}
Run Code Online (Sandbox Code Playgroud)