使用SpringMVC来实现一组对User对象操作的RESTful API,配合注释详细说明在Spring MVC中如何映射HTTP请求、如何传参、如何编写单元测试
定义Model实体类
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class StudentModel{
@Id @GeneratedValue
private Integer id;
private String name;
private Date birth;
//getter、setter
}
Controller层
测试用例
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
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.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.tutorial.springboot.AppStart;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes=AppStart.class)//MockServletContext.class
@WebAppConfiguration
public class SpringMockTest extends MockMvcResultMatchers{
//模拟mvc对象类.
private MockMvc mockMvc;
@Autowired
protected WebApplicationContext wac;
@Before() //这个方法在每个方法执行之前都会执行一遍
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); //初始化MockMvc对象
}
@Test
public void queryAllStudents() throws Exception {
String url ="/student/queryAll";
RequestBuilder request = MockMvcRequestBuilders.get(url)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mockMvc.perform(request)
.andExpect(status().isOk()) //返回的状态是200
.andDo(print()) //打印出请求和相应的内容
.andReturn();
//int status = mvcResult.getResponse().getStatus();
String content = mvcResult.getResponse().getContentAsString();//将相应的数据转换为字符串
System.out.println(content);
}
}
注意:在测试类上的注解,常用的注解有三个
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
这三个注解,只要注意第二个注解括号内的Application.class就行,把它替换为项目的启动类即可。
http://www.cnblogs.com/0201zcr/p/5756642.html