首页 > 代码库 > spring mvc 单元测试

spring mvc 单元测试

package com.sishuok.mvc.controller;


import org.junit.Assert;

import org.junit.Before;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import org.springframework.test.context.web.WebAppConfiguration;

import org.springframework.test.web.servlet.MockMvc;

import org.springframework.test.web.servlet.MvcResult;

import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import org.springframework.test.web.servlet.result.MockMvcResultHandlers;

import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import org.springframework.web.context.WebApplicationContext;


import com.sishuok.service.UserService;

@RunWith(SpringJUnit4ClassRunner.class)

@WebAppConfiguration(value = "http://www.mamicode.com/src/main/webapp")

@ContextConfiguration(value = http://www.mamicode.com/{"classpath:spring-config.xml", "classpath:spring-mvc.xml"})

public class UserControllerWebAppContextSetupTest {

@Autowired

UserService userService;

  @Autowired

  private WebApplicationContext wac;

  private MockMvc mockMvc;

  @Before

  public void setUp() {

      mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();

  }

@Test

  public void testView() throws Exception {

      MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/user/1"))

              .andExpect(MockMvcResultMatchers.view().name("user/view"))

              .andExpect(MockMvcResultMatchers.model().attributeExists("user"))

              .andDo(MockMvcResultHandlers.print())

              .andReturn();

      Assert.assertNotNull(result.getModelAndView().getModel().get("user"));

  }

}

最主要的有三个对象 

WebApplicationContext

MockMvc

MockActionResponse

MockActionResquest

这个是简单的,回头再补充



spring mvc 单元测试