2017-06-13 38 views
2

我有了通过@Value注入私有实例布尔领域的Spring MVC的REST控制器类,Spring MVC控制器单元测试:如何设置私有实例布尔型字段?

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

我们单元测试这个控制器类,我需要注入这个布尔。

我该怎么做与MockMvc

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

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

设置如下所示。

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

    @Autowired 
    private MockMvc mockMvc; 
.... 
} 

回答

2

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

     //.. 
    } 

} 
+0

那么如何改变不同'@ Test'方法的属性值?此注释适用于测试类级别。主题目标不是从属性文件获取值,而是为各种场景更改值。 –

+0

@SabirKhan然后你应该用不同的测试属性重新加载你的应用程序上下文。但它应该也可以使用反射来改变它,如上所示。查看更新的帖子。 –

+0

是的,我得到它与'controller = new IndexController(); \t \t \t \t mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); \t \t \t \t isFileIndexField = controller.getClass()。getDeclaredField(“isFileIndex”); \t \t \t \t isFileIndexField.setAccessible(true); \t \t \t \t indexServiceField = controller.getClass()。getDeclaredField(“indexService”); \t \t indexServiceField。setAccessible(真); \t \t indexServiceField.set(controller,indexService);'但你的建议是非常小的代码。 –

0

我的最佳选择是将其设置在构造和注释与@Value的构造函数的参数。然后你可以通过任何你想要的测试。

this answer

+0

我这里不明确创建控制器实例所以我认为,构造也帮不了。让我知道我是否缺少任何东西。 –