springboot项目编写测试用例

1,345 阅读1分钟

前期准备

idea默认快捷键ctrl+shift+t 通过Create New Test生成测试用例,如果没有出现再安装插件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>

<!-- 测试代码覆盖率 在父级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端

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包下

@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