基于JUnit测试Spring MVC的正确方法。(仅限Spring 3.2)

来源:互联网 发布:apache工作原理 编辑:程序博客网 时间:2024/05/16 17:20
package com.teamsun.test.JunitAnnocation;


import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;


import com.teamsun.core.linkplat.controller.RouteAction;




@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:jdbc-context.xml",
"classpath:springmvc-servlet.xml" })
public class TestController {


@Autowired
private WebApplicationContext wac;


@Autowired
private RouteAction routeaction;//你要测试的Controller


private MockMvc mockMvc;


@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(routeaction).build();
}


@Test
public void testFindPageUsers() throws Exception {
ResultActions ra = this.mockMvc.perform(MockMvcRequestBuilders
.post("/route/operate.do")
.accept(MediaType.APPLICATION_JSON).param("flag", "add")
.param("limit", "10"));
MvcResult mr = ra.andReturn();
String result = mr.getResponse().getContentAsString();
System.out.println("resutl==>"+result);
}


}
原创粉丝点击