【问题标题】:Testing for a null model attribute in Spring在 Spring 中测试空模型属性
【发布时间】:2014-01-28 11:33:39
【问题描述】:

我一直在使用 Mockito 测试我的 Spring 控制器方法,但对以下失败测试的行为感到困惑:

控制器:

@RequestMapping(value = "/getPage", method = RequestMethod.GET)
public String getPage(Model model) {

    String myString = myService.someMethod();

    model.addAttribute("myString", myString);
    return "myTemplate";
}

测试:

@Test public void testGetPage() throws Exception {

    String myString = null;

    when(mockService.someMethod()).thenReturn(myString);

    mockMvc.perform(get("/getPage"))
        .andExpect(status().isOk())
        .andExpect(model().size(1)) // this passes
        .andExpect(model().attribute("myString", myString))   // fails: "Model attribute 'myString' does not exist 
        .andExpect(model().attributeExists("myString"))    // fails: "Model attribute 'myString' does not exist 
        ;
 }

如果不是 myString 变量,那么当它返回 model().size(1) 时,测试检测到什么?有没有办法列出与模型关联的所有属性?

【问题讨论】:

    标签: java spring spring-mvc mockito


    【解决方案1】:

    模型是一个映射,其键为 myString,值为 null。要使模型大小为零,请不要向其添加任何属性。

    您可以有 1000 个属性,全部初始化为 null。大小为 1000。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 2016-07-12
      • 2021-09-18
      • 1970-01-01
      • 2017-07-27
      • 2015-02-17
      相关资源
      最近更新 更多