【问题标题】:how to test spring mvc model attributes from controller that return objects containing objects如何从返回包含对象的对象的控制器测试spring mvc模型属性
【发布时间】:2019-01-08 03:13:17
【问题描述】:

我有一个 controller 我正在尝试测试。我将 myObj 添加为属性,其中 myObj 本身就是一个对象

public class MyObj {

private List<OtherObj> otherObjList;
private SecondObj secondObj;
//getter setter

}

这是我的控制器

  @Controller
    public class MyController {
        @RequestMapping(value = "/", method = RequestMethod.GET)
        public String home(final Model model) {

           //i prepare myobj here 
            model.addAttribute("myObj",myObj);
            return "myPage";
        }

}

这是我的测试用例。我正在尝试查看第一项中的属性是否 otherObjList 是否有一些价值。这是我尝试过但不起作用的方法

mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(model().attribute("myObj.otherObjList", hasItems(hasProperty("id", is(12345)))));

【问题讨论】:

    标签: spring spring-mvc spring-boot junit mockmvc


    【解决方案1】:

    当你想测试一个普通的控制器时,我认为你在正确的轨道上,但. 符号不适合。查看以下示例测试断言:

     mockMvc.perform(get("/"))
                    .andExpect(status().isOk())
                    .andExpect(view().name("todo/list"))
                    .andExpect(forwardedUrl("/WEB-INF/jsp/todo/list.jsp"))
                    .andExpect(model().attribute("todos", hasSize(2)))
                    .andExpect(model().attribute("todos", hasItem(
                            allOf(
                                    hasProperty("id", is(1L)),
                                    hasProperty("description", is("Lorem ipsum")),
                                    hasProperty("title", is("Foo"))
                            )
                    )))
                    .andExpect(model().attribute("todos", hasItem(
                            allOf(
                                    hasProperty("id", is(2L)),
                                    hasProperty("description", is("Lorem ipsum")),
                                    hasProperty("title", is("Bar"))
                            )
                    )));
    

    也许这个页面可以帮助你:https://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-mvc-controllers-normal-controllers/

    【讨论】:

    • 我一直在使用 jsonPath 作为我的休息控制器。这不适用于控制器。
    • 能否请您先看看我的问题。我返回的对象很复杂。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 2014-08-17
    相关资源
    最近更新 更多