使用Spring MockMVC对controller做单元测试
1、对单一controller做测试。
import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; 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.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration("classpath:") @ContextConfiguration("/data/spring-test.xml") public class CommonCtrlTest { private MockMvc mockMvc; @Autowired CommonCtrl commonCtrl; @Before public void setup() { this.mockMvc = MockMvcBuilders.standaloneSetup(commonCtrl).build(); } @Test public void testHello() throws Exception { ResultActions resultActions = this.mockMvc.perform( MockMvcRequestBuilders.get("/test").accept(MediaType.APPLICATION_JSON)); MvcResult mvcResult = resultActions.andReturn(); String result = mvcResult.getResponse().getContentAsString(); System.out.println("response:" + result); } }
2、对整个环境做测试,包括Interceptor。
import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import outfox.course.weixinkaoshen.dao.AbstractTest; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; public class TestKaoshenCtrl extends AbstractTest{ @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } @Test public void testAddUser() throws Exception { mockMvc.perform((get("/test/get").param("id", "1"))) .andExpect(status().isOk()).andDo(print()); } }