概述
我们在写spring mvc controller时,一般情况下都是在浏览器测试
但是有时候,我们写的controller提供的是api接口,这时我们该怎么测试呢?
这时 spring mvc 给我们提供了一个很好的测试方法,mock test
多的不说了,直接看代码:
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
import java.util.Date;
import javax.annotation.Resource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.test.BasicRespMessage;
import org.test.controller.TestController;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
@ContextConfiguration(locations = { "classpath*:spring/app-config.xml", "classpath*:spring/mvc-config.xml" })
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class TestController extends AbstractTransactionalJUnit4SpringContextTests {
@Resource
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = webAppContextSetup(this.wac).build();
}
@Test
@Rollback(false)
public void test0() throws Exception {
TestController controller = (TestController) this.applicationContext.getBean("testController");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setMethod("POST");
request.addParameter("subject", "数学");
request.addParameter("grade", "66"); // 六年级
request.addParameter("time", new Date().getTime() + "");
request.addParameter("sign", new Date().getTime() + "");
BasicRespMessage m = controller.test0(request, response);
System.out.println("--------->" + m.getStatusCode() + "<===>" + m.getStatusDesc() + "<===>" + m.getBody());
}
@Test
public void test1() throws Exception {
this.mockMvc.perform(//
put("/test/test0")//
.param("subject", "数学") //
.param("grade", "66") // // 六年级
.param("time", new Date().getTime() + "") //
.param("sign", new Date().getTime() + "")) //
.andExpect(status().isOk())//
.andDo(print())
.andReturn();
}
}
test0 method 是直接调用controller的method
test1 method 是请求url地址
最后
以上就是坚强草莓为你收集整理的spring mvc test by mock的全部内容,希望文章能够帮你解决spring mvc test by mock所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复