springboot项目编写测试用例

前期准备

idea默认快捷键ctrl+shift+t 通过Create New Test生成测试用例,如果没有出现再安装插件JUnitGenerator V2.0

maven

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
js复制代码<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

<!-- 测试代码覆盖率 在父级POM引入-->
<dependency>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.3</version>
</dependency>
<!-- 测试代码覆盖率 在父级POM引入-->
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.3</version>
<configuration>
<includes>
<include>com/**/*</include>
</includes>
</configuration>
<executions>
<execution>
<id>pre-test</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>post-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<!--在启动模块添加-->
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.3</version>
<executions>
<execution>
<id>report-aggregate</id>
<phase>verify</phase>
<goals>
<goal>report-aggregate</goal>
</goals>
</execution>
</executions>
</plugin>

编写测试用例

controller端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
js复制代码import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.context.WebApplicationContext;
····

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@WebAppConfiguration
@ActiveProfiles("dev")
public class ControllerTest {

private static final String URL = "/demo";

@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;

@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}


@Test
public void importAll() throws Exception {
//传文件夹路径
String content = mockMvc
.perform(MockMvcRequestBuilders.post(URL + "/importAll").param("file","D://测试文件夹").contentType(MediaType.APPLICATION_JSON_UTF8))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.success").value(true))
.andReturn().getResponse().getContentAsString();
Assert.assertNotNull(content);
}

//上传文件
@Test(expected = FileNotFoundException.class)
public void readExcel() throws Exception {
String uploadFilePath = "D://测试.xlsx";
File uploadFile = new File(uploadFilePath);
String fileName = uploadFile.getName();
MockMultipartFile file = new MockMultipartFile("uploadFile", fileName, MediaType.TEXT_PLAIN_VALUE, new FileInputStream(uploadFile));
String content = mockMvc.perform(MockMvcRequestBuilders.fileUpload(URL + "/readExcel").file(file))
.andDo(print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.failed").value(false))
.andReturn().getResponse().getContentAsString();
Assert.assertNotNull(content);
}
}

@Test
public void find() throws Exception {
ArrayList<Long> longs = new ArrayList<>();
longs.add(1L);
longs.add(2L);
HashMap<Object, Object> map = Maps.newHashMap();
map.put("idList",longs);
String json = JsonUtils.toJsonString(map);
String content = mockMvc
.perform(MockMvcRequestBuilders.post(URL + "/find").content(json).contentType(MediaType.APPLICATION_JSON_UTF8))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.success").value(true))
.andReturn().getResponse().getContentAsString();
Assert.assertNotNull(content);
}

//下载文件
@Test(expected = Exception.class)
public void download() throws Exception {
Long projectId = 1L;
String excelSheetName = "Sheet1";
String filePath = "D://测试.xlsx"; //下载文件路径
mockMvc.perform(MockMvcRequestBuilders.get(URL+"/download/"+projectId))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(result -> {
result.getResponse().setCharacterEncoding("UTF-8");
MockHttpServletResponse contentResponse = result.getResponse();
InputStream contentInStream = new ByteArrayInputStream(
contentResponse.getContentAsByteArray());
XSSFWorkbook resultExcel = new XSSFWorkbook(contentInStream);
//Assert.assertEquals("multipart/form-data", contentResponse.getContentType());
XSSFSheet sheet = resultExcel.getSheet(excelSheetName);
Assert.assertNotNull(sheet);
File file = new File(filePath);
OutputStream out = new FileOutputStream(file);
resultExcel.write(out);
resultExcel.close();
Assert.assertTrue(file.exists());
});
}

@Test
public void userAreaList() throws Exception{
Cookie cookie = new Cookie("www.baidu.com","xxxxxxxxxxxxxxxxxxxxx");
cookie.setPath("/");
cookie.setMaxAge(7);
String content = mockMvc
.perform(MockMvcRequestBuilders.get(URL + "/areaList").cookie(cookie))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.failed").value(true))
.andReturn().getResponse().getContentAsString();
Assert.assertNotNull(content);
}
}

service端

service端Test同controller放在同一主test包下,均在启动model所在test包下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
js复制代码@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class DemoServiceImplTest {

@MockBean
private DemoMapper demoMapper;
@Resource
private DemoServiceImpl demoImpl;

@Test
public void listByParam() {
DataVo map = new DataVo();
map.setCityName("南昌");
//Mockito需要放在service调用前,模拟dao层返回数据,即new ArrayList<>()相当于原地TP
Mockito.when(demoMapper.listByParam(map)).thenReturn(new ArrayList<>());
List<DemoData> param = demoImpl.listByParam(map);
Assert.assertNotNull(param);
}

@Test
public void listByCityId() {
List<DemoData> param = DemoServiceImpl.listByCityId(1L, 1);
Assert.assertNotNull(param);
}
}

生成覆盖率

执行mvn -test或者mvn verify

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%