这里总结了,springboot(Maven工程) 中如何更好的写出单元测试,需要引如下包
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class)
@SpringBootTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Transactional
public class UserControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
// 基本结构如下
@Test
public void test() {
mockMvc.perform(MockMvcRequestBuilders.get("/pis/user/test?userId=67327"))
.andDo(print());
}
}
@Test
public void findOne() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/pis/user/find-one?userId=50070")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk()).andDo(print());
}
示例1 ----- Json 入参
@Test
public void add() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/pis/user/add")
.contentType(MediaType.APPLICATION_JSON)
.content("{\n" +
" \"userCode\": \"ls0ss1\",\n" +
" \"userName\": \"ls022\",\n" +
" \"departmentId\": 1,\n" +
" \"email\": \"[email protected]\",\n" +
" \"station\": \"dep\",\n" +
" \"company\": \"com1\",\n" +
" \"entryTime\": \"2001-12-12\",\n" +
" \"leaveTime\": \"\",\n" +
" \"entranceStatus\": 1\n" +
"}")
.accept(MediaType.APPLICATION_JSON))
.andDo(print());
}
示例2 -----Form 表单入参
@Test
public void addConfigInfo2() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/pis/config/add")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("key", "key-test")
.param("value", "v_test")
.param("summary", "简介")
.accept(MediaType.APPLICATION_JSON))
.andDo(print());
}
示例1 单个删除
@Test
public void delete() {
mockMvc.perform(MockMvcRequestBuilders.delete("/pis/user/delete?userId=67327"))
.andDo(print());
}
示例2 批量删除
@Test
public void delete() {
mockMvc.perform(MockMvcRequestBuilders.delete("/pis/user/delete?userId=1,2,3,4"))
.andDo(print());
}
@Test
public void importUsers() throws Exception {
File file = new File("C:\\Users\\test\\Downloads\\用户设置导出.xlsx");
MockMultipartFile firstFile = new MockMultipartFile("file", "用户设置导出.xlsx",
MediaType.TEXT_PLAIN_VALUE, new FileInputStream(file));
mockMvc.perform(MockMvcRequestBuilders.multipart("/pis/user/import").file(firstFile)
.contentType(MediaType.MULTIPART_FORM_DATA_VALUE))
.andExpect(MockMvcResultMatchers.status().isOk()).andDo(print());
}
@Test
public void templateDownload() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/pis/user/template-download")
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(MockMvcResultMatchers.status().isOk()).andDo(print());
}