51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

手机号码,快捷登录

查看: 1317|回复: 0
打印 上一主题 下一主题

[转贴] springboot项目编写测试用例

[复制链接]
  • TA的每日心情
    擦汗
    5 天前
  • 签到天数: 1027 天

    连续签到: 2 天

    [LV.10]测试总司令

    跳转到指定楼层
    1#
    发表于 2021-6-3 09:37:37 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
     前期准备
      idea默认快捷键ctrl+shift+t 通过Create New Test生成[url=][/url][url=]测试[/url]用例,如果没有出现再安装插件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.


    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-10-5 08:35 , Processed in 0.249820 second(s), 24 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表