一:RestTemplate模式 需要启动服务器
@Test
public void restTemplate() throws Exception{
String user = "{\"id\":10,\"password\":\"myPassword\",\"userName\":\"myUserName\"}";//实例请求参数
HttpHeaders headers = new HttpHeaders();//创建一个头部对象
//设置contentType 防止中文乱码
headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
headers.add("Accept", MediaType.APPLICATION_JSON_UTF8.toString());
//设置我们的请求信息,第一个参数为请求Body,第二个参数为请求头信息
//完整的方法签名为:HttpEntity<String>(String body, MultiValueMap<String, String> headers)
HttpEntity<String> strEntity = new HttpEntity<String>(user,headers);
RestTemplate restTemplate = new RestTemplate();
//使用post方法提交请求,第一参数为url,第二个参数为我们的请求信息,第三个参数为我们的相应放回数据类型,与String result对厅
//完整的方法签名为:postForObject(String url, Object request, Class<String> responseType, Object... uriVariables) ,最后的uriVariables用来拓展我们的请求参数内容。
String result = restTemplate.postForObject("http://localhost:8080/springMVC/user/getUser1",strEntity,String.class);
System.out.println(result);//运行方法,这里输出:
}
二:MockMvc模式 无需启动服务器
-
构建项目--pom里面一些关键的依赖包
<!--用于数据库管理-->
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<!--测试依赖包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--内存数据库用于测试-->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
spirng boot
提供了测试框架我们只要引入spring-boot-starter-test
就可以了。spirng boot
还集成了flyway
flyway简单入门,我们可以用这个工具来帮我们初始化测试用的数据表。 当然不用flyway
,hibernate
也有反向生成数据表的功能。H2
是一个免安装内嵌在运行程序里的一个数据库,这里我用它来作为我们的单元测试使用的数据库。这个数据库运行在内存中生命周期与单元测试生命周期一样。也就是说每次运行都是新的库。单元测试的数据是不会写到mysql库里的。@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class UserControllerTest { @Autowired private MockMvc mvc; @Test public void test() throws Exception { RequestBuilder request; // 1、get查一下user列表应该为空 request = get("/user"); mvc.perform(request) .andExpect(status().isOk()) .andExpect(content().string(equalTo("[]"))); // 2、post提交一个user request = post("/user/") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content("{\"name\":\"zxc\",\"age\":18}"); mvc.perform(request) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.name",is("zxc"))); // 3、get查一下user列表,应该不为空 request = get("/user"); mvc.perform(request) .andExpect(status().isOk()) .andExpect(content().string(not(""))) .andExpect(content().string(not("[]"))); // 4、get查一下user id 等于1的用户,应该不为空,age等于18 request = get("/user/{id}",1); mvc.perform(request) .andExpect(status().isOk()) .andExpect(content().string(not(""))) .andExpect(jsonPath("$.age").value(18)); // 4、put更新用户zxc request = put("/user") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content("{\"id\":1,\"name\":\"zxc\",\"age\":20}"); mvc.perform(request) .andExpect(status().isOk()) .andDo(print()) .andExpect(jsonPath("$.age").value(20)) .andExpect(jsonPath("$.name").value("zxc")); } }