码迷,mamicode.com
首页 > 编程语言 > 详细

spring mvc 单元测试

时间:2014-12-12 19:28:06      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:style   io   sp   for   on   bs   cti   ef   as   

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 = "src/main/webapp")

@ContextConfiguration(value = {"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 单元测试

标签:style   io   sp   for   on   bs   cti   ef   as   

原文地址:http://my.oschina.net/internetafei/blog/355628

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!