SpringMVC对REST服务使用mockmvc 做测试
- pom.xml配置
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
在test包路径下创建测试类测试
基类:
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.context.WebApplicationContext;
/**
* Created by Administrator on 2016/9/8.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("src/main/resources/")
@ContextHierarchy({
@ContextConfiguration(name="parent",locations = "classpath:applicationContext.xml"),
@ContextConfiguration(name = "child", locations = "classpath:applicationContext-mvc.xml")
}
)
public class TestBase {
@Autowired
WebApplicationContext wac;
}
实现类:
import org.junit.Before;
import org.junit.Test;
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.setup.MockMvcBuilders;
/**
* Created by Administrator on 2016/9/8.
*/
public class RestTest extends TestBase {
private MockMvc mockMvc;
@Before
public void sstUp(){
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void testView() throws Exception {
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/test"))
.andDo(MockMvcResultHandlers.print())
.andReturn();
}
}