preparation

Idea Default shortcut CTRL + Shift + T Generate Test cases by creating New Test. If not, install the plug-in JUnitGenerator V2.0

maven

<! -- 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><! -- Test code coverage introduced in parent POM --><dependency>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.3</version>
</dependency><! -- Test code coverage introduced in parent 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><! -- Add boot module --><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>
Copy the code

Write test cases

The controller side

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;
importorg.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 {
    // Pass the folder path
    String content = mockMvc
        .perform(MockMvcRequestBuilders.post(URL + "/importAll").param("file"."D:// test folder").contentType(MediaType.APPLICATION_JSON_UTF8))
        .andDo(MockMvcResultHandlers.print())
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.jsonPath("$.success").value(true))
        .andReturn().getResponse().getContentAsString();
    Assert.assertNotNull(content);
  }

  // Upload the file
  @Test(expected = FileNotFoundException.class)
  public void readExcel() throws Exception {
    String uploadFilePath = "D: / / test. 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);
}

  // Download the file
  @Test(expected = Exception.class)
  public void download() throws Exception {
    Long projectId = 1L;
    String excelSheetName = "Sheet1";
    String filePath = "D: / / test. XLSX";  // Download file path
    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); }}Copy the code

The service side

The service Test and controller are stored in the same main Test package under the Test package where the model is started

@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("Nanchang");
    //Mockito needs to be placed before the service call, where the mock DAO layer returns data, i.e. new ArrayList<>() equals TP in place
    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); }}Copy the code

Generation coverage

Run mVN-test or MVN verify