引入单元的是模块
在项目引入单元测试包 - 以spring-boot项目为例:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
编写单元测试类
@SpringBootTest(classes = SpringBootGitApplication.class)
@RunWith(SpringRunner.class)
public class SpringBootMockMvc {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setup(){
// 测试代码执行前,需要执行的代码
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test // 上传文件测试
public void testFile() throws Exception {
String result = mockMvc.perform(MockMvcRequestBuilders.multipart("/test/file")
// MockMultipartFile类参数 1.属性名,2.文件的名字,3.内容类型,4.上传内容字节
.file(new MockMultipartFile("file",
"test.txt",
"multipart/form-data",
"hello upload".getBytes())))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
@Test // get请求测试
public void testGet() throws Exception {
String result = mockMvc.perform(MockMvcRequestBuilders.get("/"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
@Test // post请求测试
public void testPost() throws Exception {
Date date = new Date();
System.out.println(date.getTime());
String content = "{\"username\":\"li wen ya\",\"password\":null,\"birthday\":"+date.getTime()+"}";
String result = mockMvc.perform(MockMvcRequestBuilders.post("/user")
.contentType(MediaType.APPLICATION_JSON)
.content(content))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1))
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
}
接收类接口
@Controller
@RequestMapping("/test")
public class SpringTestController {
@ResponseBody
@GetMapping("/one")
public String test(String name){
System.out.println(name);
return "hello world";
}
@ResponseBody
@PostMapping("/user")
public User testPost(@RequestBody User user){
return user;
}
@ResponseBody
@RequestMapping("/file")
public String file(MultipartFile file){
System.out.println(file.getName());
System.out.println(file.getOriginalFilename());
System.out.println(file.getSize());
return "成功";
}
}
user对象
public class User {
/**
* 用户名称
*/
private String username;
/**
* 用户密码
*/
private String password;
/**
* 生日
*/
private Date birthday;
// get/set方法省略
}
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理