• 如何优雅的写出一个完整的测试用例


    springboot-测试用例

    UcApplicationTests启动类

    package com.izkml.mlyun.uc;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class UcApplicationTests {
    
        @Test
        public void contextLoads() {
        }
    
    }
    

    ControllerTestBase基础类

    package com.izkml.mlyun.uc.user.controller;
    
    import com.izkml.mlyun.uc.UcApplicationTests;
    import org.junit.Before;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.boot.test.web.client.TestRestTemplate;
    import org.springframework.boot.web.server.LocalServerPort;
    
    import java.net.URL;
    
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    public abstract class ControllerTestBase extends UcApplicationTests {
        @LocalServerPort
        protected int port;
        @Autowired
        protected TestRestTemplate template;
        protected URL base;
    
        protected abstract String getPath();
    
        @Before
        public void setUp() throws Exception {
            this.base = new URL("http://localhost:" + port + getPath());
        }
    }
    

    DeptControllerTest测试类

    package com.izkml.mlyun.uc.user.controller;
    
    import com.izkml.mlyun.framework.common.result.JsonResult;
    import com.zkml.common.util.JsonUtil;
    import org.junit.Test;
    import org.springframework.http.*;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import static org.junit.Assert.*;
    
    /**
     * Created by fanghui on 2019/11/12.
     */
    public class DeptControllerTest extends ControllerTestBase {
    
        @Override
        protected String getPath() {
            return "/dept";
        }
    
        @Test
        public void insert() throws Exception {
            String url = base + "";
            Map<String, Object> paramMap = buildParam("单元测试部门1688", "测试1", "1", "18110275751", "1");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<String> httpEntity = new HttpEntity(JsonUtil.getJsonString(paramMap), headers);
            ResponseEntity response = template.postForEntity(url, httpEntity, JsonResult.class);
            System.out.println(response.getBody());
        }
    
        @Test
        public void bachInsert() throws Exception {
            String url = base + "/batchInsert";
            List<Map<String, Object>> paramMapList = new ArrayList<>();
            paramMapList.add(buildParam("单元测试部门1488", "测试1", "1", "18110275751", "1"));
            paramMapList.add(buildParam("单元测试部门1499", "测试2", "1", "18110275751", "1"));
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<String> httpEntity = new HttpEntity(JsonUtil.getJsonString(paramMapList), headers);
            ResponseEntity response = template.postForEntity(url, httpEntity, JsonResult.class);
            System.out.println(response.getBody());
        }
    
        private Map<String, Object> buildParam(String name, String orgId, String parentId, String fixedPhone, String sort) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("name", name);
            paramMap.put("orgId", orgId);
            paramMap.put("parentId", parentId);
            paramMap.put("fixedPhone", fixedPhone);
            paramMap.put("sort", sort);
            return paramMap;
        }
    
        @Test
        public void update() throws Exception {
            String url = base + "";
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("id", "bmJwwK4zTZOLBJHjS7A");
            paramMap.put("fixedPhone", "22222");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<String> httpEntity = new HttpEntity(JsonUtil.getJsonString(paramMap), headers);
            ResponseEntity response = template.exchange(url, HttpMethod.PUT, httpEntity, JsonResult.class);
            System.out.println(response.getBody());
        }
    
        @Test
        public void logicDelete() throws Exception {
            String url = base + "/logicDelete/bmJwwK4zTZOLBJHjS7A";
            Map<String, Object> paramMap = new HashMap<>();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<String> httpEntity = new HttpEntity(JsonUtil.getJsonString(paramMap), headers);
            ResponseEntity response = template.exchange(url, HttpMethod.POST, httpEntity, JsonResult.class);
            System.out.println(response.getBody());
        }
    
        @Test
        public void findDeptTree() {
            String url = base + "/findDeptTree?orgId=12323";
            Map<String, Object> paramMap = new HashMap<>();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<String> httpEntity = new HttpEntity(JsonUtil.getJsonString(paramMap), headers);
            ResponseEntity response = template.exchange(url, HttpMethod.GET, httpEntity, JsonResult.class);
            System.out.println(response.getBody());
        }
    }
    

    springboot-controller测试用例

    UcApplicationTests启动类

    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class UcApplicationTests {
    
       @Test
       public void contextLoads() {
       }
    }
    

    ControllerTestBase基础类

    import com.izkml.mlyun.uc.UcApplicationTests;
    import org.junit.Before;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.boot.test.web.client.TestRestTemplate;
    import org.springframework.boot.web.server.LocalServerPort;
    
    import java.net.URL;
    
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    public abstract class ControllerTestBase extends UcApplicationTests {
        @LocalServerPort
        protected int port;
        @Autowired
        protected TestRestTemplate template;
        protected URL base;
    
        protected abstract String getPath();
    
        @Before
        public void setUp() throws Exception {
            this.base = new URL("http://localhost:" + port + getPath());
        }
    }
    

    测试类

    import com.izkml.mlyun.framework.common.result.JsonResult;
    import com.zkml.common.util.JsonUtil;
    import org.junit.Test;
    import org.springframework.http.*;
    
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * Created by fanghui on 2019/11/12.
     */
    public class DeptControllerTest extends ControllerTestBase {
    
        @Override
        protected String getPath() {
            return "/dept";
        }
    
        @Test
        public void insert() throws Exception {
            String url = base + "";
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("name", "单元测试部门");
            paramMap.put("orgId", "测试");
            paramMap.put("parentId", "1");
            paramMap.put("fixedPhone", "18110275751");
            paramMap.put("sort", "1");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<String> httpEntity = new HttpEntity(JsonUtil.getJsonString(paramMap), headers);
            ResponseEntity response = template.postForEntity(url, httpEntity, JsonResult.class);
            System.out.println(response.getBody());
        }
        
        
        @Test
    public void update() throws Exception {
        String url = base + "";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", "bmJwwK4zTZOLBJHjS7A");
        paramMap.put("fixedPhone", "22222");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> httpEntity = new HttpEntity(JsonUtil.getJsonString(paramMap), headers);
        ResponseEntity response = template.exchange(url, HttpMethod.PUT, httpEntity, JsonResult.class);
        System.out.println(response.getBody());
    }
    
    @Test
    public void logicDelete() throws Exception {
        String url = base + "/logicDelete/bmJwwK4zTZOLBJHjS7A";
        Map<String, Object> paramMap = new HashMap<>();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> httpEntity = new HttpEntity(JsonUtil.getJsonString(paramMap), headers);
        ResponseEntity response = template.exchange(url, HttpMethod.POST, httpEntity, JsonResult.class);
        System.out.println(response.getBody());
    }
    
    @Test
    public void findDeptTree() {
        String url = base + "/findDeptTree?orgId=12323";
        Map<String, Object> paramMap = new HashMap<>();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> httpEntity = new HttpEntity(JsonUtil.getJsonString(paramMap), headers);
        ResponseEntity response = template.exchange(url, HttpMethod.GET, httpEntity, JsonResult.class);
        System.out.println(response.getBody());
    }
    
    @Test
    public void get() throws Exception {
        String url = base + "/get?id=" + "1";
        ResponseEntity response = template.getForEntity(url, String.class);
        System.out.println(response.getBody().toString());
    }
    

    时间测试类

    package com.izkml.mlyun.uc.user.controller;
    
    import com.fasterxml.jackson.annotation.JsonFormat;
    import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
    import com.fasterxml.jackson.databind.annotation.JsonSerialize;
    import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
    import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
    import com.izkml.mlyun.framework.database.model.MLBaseModel;
    import com.izkml.mlyun.framework.database.mybatis.registermapper.MLBaseMapper;
    import io.swagger.annotations.ApiModelProperty;
    import lombok.Getter;
    import lombok.Setter;
    import lombok.ToString;
    import org.apache.ibatis.annotations.Update;
    import org.apache.ibatis.logging.nologging.NoLoggingImpl;
    import org.junit.After;
    import org.junit.Assert;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.modelmapper.ModelMapper;
    import org.modelmapper.convention.MatchingStrategies;
    import org.mybatis.spring.SqlSessionTemplate;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.format.annotation.DateTimeFormat;
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.MediaType;
    import org.springframework.stereotype.Service;
    import org.springframework.test.annotation.Rollback;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.util.LinkedMultiValueMap;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.client.RestTemplate;
    import tk.mybatis.mapper.mapperhelper.MapperHelper;
    
    import javax.annotation.PostConstruct;
    import javax.persistence.Table;
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * 测试LocalDateTime controller接收、
     */
    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
    @Transactional //支持事物,@SpringBootTest 事务默认自动回滚
    @Rollback
    @Configuration //这里必须加,要不然内部的@Controller等无法被扫描,或者可以实现ImportBeanDefinitionRegistrar接口进行手动注册
    public class DateTest {
    
        public static final String TIME = "2019-12-03 16:52:59";
    
        public static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
        @Autowired
        DateServiceTest dateServiceTest;
    
        @Test
        public void test() throws Exception {
            requestTest();
            copyTest();
            dbTest();
        }
    
        @After
        public void after() {
            System.out.println("启动数据库事务回滚,不留一点痕迹");
        }
    
        private void dbTest() {
            dateServiceTest.createTable();
            DateModel dateModel = new DateModel();
            dateModel.setDate(LocalDateTime.parse(TIME, dateTimeFormatter));
            dateModel.setUserId("2");
            dateModel.setId("1");
            dateServiceTest.insert(dateModel);
            dateModel = dateServiceTest.get(dateModel.getId());
            equalTime(dateModel.getDate());
            System.out.println("存取DB正常" + dateModel);
        }
    
        private void requestTest() {
            System.out.println("----------测试controller使用LocalDateTime接收返回时间参数----------");
            String url = "http://localhost:8202";
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("date", TIME);
            paramMap.put("userId", "1");
    
            //requestBody 请求
            DateModel dateModel = new RestTemplate().postForObject(url + "/dateTest-RequestBody", paramMap, DateModel.class);
            equalTime(dateModel.getDate());
            System.out.println("requestBody接收返回LocalDateTime正常" + dateModel);
    
            //Get 请求
            paramMap.put("userId", "2");
            dateModel = new RestTemplate().getForObject(url + "/dateTest-GET?date={date}&userId={userId}", DateModel.class, paramMap);
            equalTime(dateModel.getDate());
            System.out.println("Get接收返回LocalDateTime正常" + dateModel);
    
            //post 请求
            HttpHeaders headers = new HttpHeaders();
            LinkedMultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<String, String>();
            multiValueMap.add("date", TIME);
            multiValueMap.add("userId", "3");
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<LinkedMultiValueMap<String, String>> httpEntity = new HttpEntity(multiValueMap, headers);
            dateModel = new RestTemplate().postForObject(url + "/dateTest-POST", httpEntity, DateModel.class);
            equalTime(dateModel.getDate());
            System.out.println("post接收返回LocalDateTime正常" + dateModel);
        }
    
        private void copyTest() {
            System.out.println("----------测试使用ModelMapper copy LocalDateTime----------");
            ModelMapper modelMapper = new ModelMapper();
            modelMapper.getConfiguration().setFullTypeMatchingRequired(true);
            modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
    
            DateModel dateModel = new DateModel();
            dateModel.setDate(LocalDateTime.parse(TIME, dateTimeFormatter));
            dateModel.setUserId("1");
    
            DateModelCopy dateModelCopy = modelMapper.map(dateModel, DateModelCopy.class);
            equalTime(dateModelCopy.getDate());
    
            System.out.println("ModelMapper copy LocalDateTime 成功");
            System.out.println("resource " + dateModel + "---------target" + dateModelCopy);
        }
    
        private void equalTime(LocalDateTime localDateTime) {
            Assert.assertEquals(localDateTime.format(dateTimeFormatter), TIME);
        }
    
        @RestController
        public static class DateControllerTest {
    
            @PostMapping("/dateTest-RequestBody")
            public DateModel dateTestRequestBody(@RequestBody DateModel dateModel) {
                return dateModel;
            }
    
            @GetMapping("/dateTest-GET")
            public DateModel dateTestGet(DateModel dateModel) {
                return dateModel;
            }
    
            @PostMapping("/dateTest-POST")
            public DateModel dateTest(DateModel dateModel) {
                return dateModel;
            }
        }
    
        @Service
        public static class DateServiceTest {
            private DateTestMapper dateTestMapper;
    
            @Autowired
            SqlSessionTemplate sqlSessionTemplate;
    
            private MapperHelper mapperHelper = new MapperHelper();
    
            @PostConstruct
            public void init() {
                sqlSessionTemplate.getConfiguration().setLogImpl(NoLoggingImpl.class);
                sqlSessionTemplate.getConfiguration().addMapper(DateTestMapper.class);
                mapperHelper.registerMapper(DateTestMapper.class);
    
                //这里是个bug,在configuration.addMapper里面添加MapperStatement id的组装方式
                // final String mappedStatementId = type.getName() + "." + method.getName();
                //最终 id = com.izkml.mlyun.uc.user.controller.DateControllerTest$DateTestMapper.selectOne 注意有个$
    
                //在processConfiguration中 id的组装方式mapperInterface.getCanonicalName()
                //最终 id = com.izkml.mlyun.uc.user.controller.DateControllerTest.DateTestMapper $变成了.
    
                //这里可以选择改写mapperHelper.processConfiguration 或者使用 mapperHelper.processConfiguration(Configuration configuration)
                //mapperHelper.processConfiguration(sqlSessionTemplate.getConfiguration(),DateTestMapper.class);
                mapperHelper.processConfiguration(sqlSessionTemplate.getConfiguration());
                dateTestMapper = sqlSessionTemplate.getMapper(DateTestMapper.class);
            }
    
            public void createTable() {
                System.out.println("初始化date_test表");
                dateTestMapper.createTable();
            }
    
            public void insert(DateModel dateModel) {
                dateTestMapper.insert(dateModel);
            }
    
            public DateModel get(String id) {
                return dateTestMapper.selectByPrimaryKey(id);
            }
        }
    
        @Getter
        @Setter
        @ToString
        @Table(name = "date_test")
        public static class DateModel extends MLBaseModel<String> {
    
            @ApiModelProperty(value = "更新时间", hidden = true)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            @JsonSerialize(using = LocalDateTimeSerializer.class)
            @JsonDeserialize(using = LocalDateTimeDeserializer.class, as = LocalDateTime.class)
            private LocalDateTime date;
    
            private String userId;
        }
    
        @Getter
        @Setter
        @ToString
        public static class DateModelCopy {
    
            @ApiModelProperty(value = "更新时间", hidden = true)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            @JsonSerialize(using = LocalDateTimeSerializer.class)
            @JsonDeserialize(using = LocalDateTimeDeserializer.class, as = LocalDateTime.class)
            private LocalDateTime date;
    
            private String userId;
        }
    
        public interface DateTestMapper extends MLBaseMapper<DateModel> {
            @Update("CREATE TABLE if not exists `date_test` (" +
                    "  `id` VARCHAR(80) NOT NULL," +
                    "  `user_id` VARCHAR(80) NOT NULL," +
                    "  `date` DATETIME DEFAULT NULL," +
                    "  `created_by` VARCHAR(255) CHARACTER SET utf8 DEFAULT NULL," +
                    "  `updated_by` VARCHAR(255) CHARACTER SET utf8 DEFAULT NULL," +
                    "  `created_at` DATETIME DEFAULT NULL," +
                    "  `updated_at` DATETIME DEFAULT NULL," +
                    "  PRIMARY KEY (`id`)" +
                    ") ENGINE=INNODB DEFAULT CHARSET=utf8mb4")
            void createTable();
        }
    }
    
  • 相关阅读:
    java实现趣味拼算式
    windows下安装docker
    Docker_入门?只要这篇就够了!(纯干货适合0基础小白)
    网关支付、银联代扣通道、快捷支付、银行卡支付分别是怎么样进行支付的?
    【深度解析】第三方支付的分类、接口与支付流程
    去外包公司的伙伴们小心了!——亲身经历,数数外包公司的坑
    一个tomcat下部署多个项目或一个服务器部署多个tomcat
    tomcat部署web应用的4种方法以及部署多个应用
    datatables增删改查的实现
    基于SpringMVC+Bootstrap+DataTables实现表格服务端分页、模糊查询
  • 原文地址:https://www.cnblogs.com/fangh816/p/13438255.html
Copyright © 2020-2023  润新知