为什么ModelAtribute传递为null?

时间:2013-10-17 12:55:22

标签: java testing spring-mvc request mockito

我开发了下一个目标类

class Person{
    public Person(){}
    public Person(String name) {
        super();
        this.name = name;
    }

    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

下一个控制器:

@Controller
        private static class SampleController {


                @RequestMapping(value="/path", method=RequestMethod.POST)
                public String path(@Valid @ModelAttribute("person") Person person, BindingResult result, Model model) {
                    model.addAttribute("name",person.getName()); 
                    System.out.println(person.getName());
                    return "view";
                }
        }

和下一个测试:

public class ModelAssertionTests {

        private MockMvc mockMvc;

        @Before
        public void setup() {

                SampleController controller = new SampleController("a string value", 3, new Person("a name"));

                this.mockMvc = standaloneSetup(controller)
                                .defaultRequest(get("/"))
                                .alwaysExpect(status().isOk())
                                .build();
        }
        @Test
        public void testTest() throws Exception {
                Person person = new Person("name");
                mockMvc.perform(post("/path").sessionAttr("person", person));
        }
}

启用调试模式

在这一行:

 mockMvc.perform(post("/path").sessionAttr("person", person));

我明白了

enter image description here

当我转到控制器方法时:

 model.addAttribute("name",person.getName()); 

我明白了

enter image description here

是什么原因?

如何解决?

1 个答案:

答案 0 :(得分:3)

这是因为mockMvc请求中的sessionAttr("person", person)person设置为会话属性,而@ModelAttribute则注释模型属性

要将会话变量放入模型中(从而解决问题),请使用@SessionAttributes注释:

@Controller
@SessionAttributes("person")
private static class SampleController {
    ...
}

了解更多here

顺便说一句,您的控制器应该是public,而不是private static