Spring MVC测试失败

时间:2015-08-06 15:42:56

标签: spring testing model-view-controller

我正在使用Spring MVC Test框架为我的应用程序编写简单的集成测试。我有两个基本测试用例:

  1. 正确填写添加链接表单(输入URL和可选说明输入字段),并通过POST将链接添加到数据库,然后将客户端重定向到/ link URL。
  2. 添加链接表单为空,因此会显示/ links / create视图,并显示BindingResult的表单错误。
  3. testAddLink()测试成功通过,但testAddEmptyLink()测试方法出现问题。 在此测试中,'链接/创建'应该呈现视图,我应该在表达式

    后获得200状态代码
    result.hasErrors()
    

    是真的。

    但是,我收到302响应,应该在表单中没有错误时发送(URL已正确设置) 似乎测试方法testAddEmptyLink()无法使用BindingResult处理表单错误。

    您是否有任何想法可能导致无法处理表单错误?

    提前致谢。

    链接实体

    @Entity
    @Table(name = "links")
    public class Link {
    
    @Id @GeneratedValue
    private Integer ID;
    
    @Column(name = "url") @NotNull @NotEmpty @URL
    private String URL;
    
    private String description;
    
    @Column(name="created_at", nullable = false)
    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    private LocalDateTime createdAt;
    
    @Column(name="updated_at", nullable = true)
    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
    private LocalDateTime updatedAt;
    
    @ManyToOne
    @JoinColumn(name = "category_id")
    private Category category;
    
    public Integer getID() {
        return ID;
    }
    
    public void setID(Integer ID) {
        this.ID = ID;
    }
    
    public String getURL() {
        return URL;
    }
    
    public void setURL(String URL) {
        this.URL = URL;
    }
    
    public String getDescription() {
        return description;
    }
    
    public void setDescription(String description) {
        this.description = description;
    }
    
    public LocalDateTime getCreatedAt() {
        return createdAt;
    }
    
    public void setCreatedAt(LocalDateTime createdAt) {
        this.createdAt = createdAt;
    }
    
    public LocalDateTime getUpdateddAt() {
        return updatedAt;
    }
    
    public void setUpdateddAt(LocalDateTime updateddAt) {
        this.updatedAt = updateddAt;
    }
    
    public LocalDateTime getUpdatedAt() {
        return updatedAt;
    }
    
    public void setUpdatedAt(LocalDateTime updatedAt) {
        this.updatedAt = updatedAt;
    }
    
    public Category getCategory() {
        return category;
    }
    
    public void setCategory(Category category) {
        this.category = category;
    }
    
    }
    

    LinkController

    @Controller
    public class LinkController {
    
    @Autowired(required = true) @Qualifier(value = "linkService")
    private LinkService linkService;
    
    @Autowired
    private CategoryService categoryService;
    
    @RequestMapping(value = "/links")
    public String getLinks(Model model) {
        model.addAttribute("results", linkService.getLinks());
    
        return "links/index";
    }
    
    @RequestMapping(value = "/links/create", method = RequestMethod.GET)
    public ModelAndView showLinkForm() {
        ModelAndView model = new ModelAndView("links/create");
        model.addObject("link", new Link());
        model.addObject("categories", categoryService.getCategories());
        return model;
    }
    
    @RequestMapping(value = "/links/create", method = RequestMethod.POST)
    public String addLink(@Valid @ModelAttribute("link") Link link, BindingResult result, Model model) {
        if (result.hasErrors()) {
            model.addAttribute("categories", categoryService.getCategories());
            return "links/create";
        }
    
        linkService.addLink(link);
    
        return "redirect:/links";
    }
    }
    

    LinkControllerTest

    @ContextConfiguration(classes = {AppInitializer.class})
    @RunWith(SpringJUnit4ClassRunner.class)
    public class LinkControllerTest {
    
    @Mock
    private LinkService linkService;
    
    @InjectMocks
    private LinkController linkController;
    
    private MockMvc mockMvc;
    
    @Before
    public void setUp() {
        // Process mock annotations
        MockitoAnnotations.initMocks(this);
    
        this.mockMvc = MockMvcBuilders.standaloneSetup(linkController).build();
    }
    
    @Test
    public void testAddLink() throws Exception {
        mockMvc.perform(post("/links/create")
            .param("URL", "http://test.com")
            .param("description", "Lorem Ipsum")
            .param("category.ID", "1"))
            .andExpect(status().is3xxRedirection())
            .andExpect(view().name("redirect:/links"));
    }
    
    @Test
    public void testAddEmptyLink() throws Exception {
        mockMvc.perform(post("/links/create")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .sessionAttr("link", new Link())
        )
                .andExpect(status().isOk())
                .andExpect(view().name("links/create"))
                .andExpect(forwardedUrl("/WEB-INF/views/links/create.jsp"))
                .andExpect(model().attributeHasFieldErrors("link", "URL", "description"))
                .andExpect(model().attribute("link", hasProperty("URL", isEmptyOrNullString())))
                .andExpect(model().attribute("link", hasProperty("description", isEmptyOrNullString())));
    }
    }
    

    create.jsp(查看)

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
    <!DOCTYPE html>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
            <title>Create Category</title>
        </head>
        <body>
            <form:form action="" modelAttribute="category">
                <div>
                    <form:label path="name">Name</form:label>
                    <form:input path="name" />
                    <form:errors path="name" cssClass="error"></form:errors>
                </div>
                <div>
                    <form:label path="description">Description</form:label>
                    <form:input path="description" />
                    <form:errors path="description" cssClass="error"></form:errors>
                </div>
                <div>
                    <input type="submit" value="Create Category">
                    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
                </div>
            </form:form>
        </body>
    </html>
    

0 个答案:

没有答案