单元测试(一)——SpringBoot建立单元测试

原创
2018/11/12 11:16
阅读数 1.2W

在Spring项目中,对于controller、service、dao各层都需要建立单元测试项。对应不同的分层,我们可以使用junit和mock不同的方式。然而有些情况会需要启动spring容器来测试业务逻辑在容器内能否正常运行,针对此情况可参考如下单元测试方式。

SpringBoot增加依赖

	<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test<artifactId>
        <scope>test</scope>
    </dependency>

建立测试基类

  • 新建JUnitBaseTest.java
package com.lucas.device;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.util.StopWatch;

import lombok.extern.slf4j.Slf4j;

/**
 * <Description> <br>
 * 
 * @author xubin<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2018年9月27日 <br>
 */

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class JUnitBaseTest {

    /**
     * sw 计时器<br>
     */
    public static StopWatch sw = null;

    /**
     * Description: <br>
     * 
     * @author xubin<br>
     * @taskId <br>
     * @throws java.lang.Exception <br>
     */
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        sw = new StopWatch();
    }

    /**
     * Description: <br>
     * 
     * @author xubin<br>
     * @taskId <br>
     * @throws java.lang.Exception <br>
     */
    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        log.info("**************************************************************");
        log.info("单元测试计时统计:{}", sw.prettyPrint());
        log.info("**************************************************************");
    }

    /**
     * Description: <br>
     * 
     * @author xubin<br>
     * @taskId <br>
     * @throws java.lang.Exception <br>
     */
    @Before
    public void setUp() throws Exception {
        log.info("开始测试-----------------");
    }

    /**
     * Description: <br>
     * 
     * @author xubin<br>
     * @taskId <br>
     * @throws java.lang.Exception <br>
     */
    @After
    public void tearDown() throws Exception {
        sw.stop();
        log.info("测试结束-----------------");
    }
}

  • @BeforeClass 基类执行前触发
  • @AfterClass 基类执行后触发
  • @Before 每个@Test方法调用前触发
  • @After 每个@Test方法调用后触发

测试Case

  • service层单元测试示例 DeviceInfoTest.java
package com.lucas.device.service;

import static org.junit.Assert.fail;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.data.redis.core.StringRedisTemplate;

import com.lucas.core.common.PageInfo;
import com.lucas.device.JUnitBaseTest;
import com.lucas.device.bo.DeviceInfoBO;
import com.lucas.device.entity.DeviceInfoEntity;
import com.lucas.device.entity.cache.DeviceCache;
import com.phlico.common.framework.tool.unique.IdWorkerUtil;
import com.phlico.common.framework.web.util.JsonUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * <Description> <br>
 * 
 * @author xubin<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate Nov 4, 2018 <br>
 */

@Slf4j
public class DeviceInfoTest extends JUnitBaseTest {

    /**
     * deviceInfoService <br>
     */
    @Resource(name = "deviceInfoServiceImpl2")
    private DeviceInfoService deviceInfoService;

    /**
     * deviceRedisTemplate <br>
     */
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * appKeyArr <br>
     */
    public static final String[] appKeyArr = {
            "2e2b380a56e7464aa678294c2c345545", "e2c85a1d245844fd9bdb14f0d0fc868a", "fa58f5306eb64ce094fe65fec6261587"
    };

    /**
     * Description: <br>
     * 
     * @author xubin<br>
     * @taskId <br>
     *         <br>
     */
    @Ignore
    @Test
    public void saveTest() {
        log.info("设备保存");
        sw.start("设备保存");
        try {
            DeviceInfoBO deviceInfoBO = new DeviceInfoBO();
            deviceInfoBO.setAppKey("2e2b380a56e7464aa678294c2c345545");
            deviceInfoBO.setDeviceName("test2");
            deviceInfoBO.setDeviceCode("EE-FF-GG");
            deviceInfoBO.setDeviceDesc("测试设备1");
            deviceInfoBO.setDeviceType("bcb0ca4ef0eb463aa76a5bc0ccee1b85");
            deviceInfoBO.setDeviceState("b9cf9e01a5534487919a77f21c34c93c");
            deviceInfoBO.setDeviceIpv4("192.168.109.12");
            deviceInfoBO.setDevicePort(8088);
            deviceInfoBO.setDeviceMac("ED:AS:ZQ:QS");
            deviceInfoBO.setProtocol(0);
            deviceInfoService.save(deviceInfoBO);
        } catch (Exception e) {
            fail("设备保存异常");
        }
    }

    /**
     * Description: <br>
     * 
     * @author xubin<br>
     * @taskId <br>
     *         <br>
     */
    @Ignore
    @Test
    public void updateTest() {
        log.info("设备修改");
        sw.start("设备修改");
        try {
            DeviceInfoBO deviceInfoBO = new DeviceInfoBO();
            deviceInfoBO.setAppKey("2e2b380a56e7464aa678294c2c345545");
            deviceInfoBO.setDeviceName("测试设备-" + appKeyArr[(int) (Math.random() * appKeyArr.length)]);
            deviceInfoBO.setDeviceCode("EE-FF-GG");
            deviceInfoBO.setDeviceDesc("测试设备2");
            deviceInfoBO.setDeviceState("b9cf9e01a5534487919a77f21c34c93c");
            deviceInfoBO.setDeviceIpv4("192.168.109.122");
            deviceInfoBO.setDevicePort(8089);
            deviceInfoBO.setDeviceMac("ED:AS:ZQ:QS:DA");
            deviceInfoBO.setProtocol(0);
            deviceInfoService.update(deviceInfoBO);
        } catch (Exception e) {
            fail("设备修改异常");
        }
    }

    /**
     * Description: <br>
     * 
     * @author xubin<br>
     * @taskId <br>
     *         <br>
     */
    @Ignore
    @Test
    public void delDeviceByCodesTest() {
        log.info("设备删除");
        sw.start("设备删除");
        try {
            deviceInfoService.delDevicesByCode("2e2b380a56e7464aa678294c2c345545", "EE-FF-GG", null, null, null);
        } catch (Exception e) {
            fail("设备删除异常");
        }
    }

    /**
     * Description: <br>
     * 
     * @author xubin<br>
     * @taskId <br>
     *         <br>
     */
    @Ignore
    @Test
    public void delDeviceByIdsTest() {
        log.info("按id删除设备");
        sw.start("按id删除设备");
        try {
            deviceInfoService.delete("2e2b380a56e7464aa678294c2c345545", "d99b77637c1e421db89ac89579d43eef,00d2105433d94106a88596f275e58d41", null,
                    null, new Date());
        } catch (Exception e) {
            fail("按id删除设备异常");
        }
    }

    /**
     * Description: <br>
     * 
     * @author xubin<br>
     * @taskId <br>
     *         <br>
     */
    @Ignore
    @Test
    public void queryEntityListByPageTest() {
        log.info("分页查询设备");
        sw.start("分页查询设备");
        try {
            DeviceInfoBO bo = new DeviceInfoBO();
            bo.setAppKey("2e2b380a56e7464aa678294c2c345545");
            PageInfo<DeviceInfoBO> list = deviceInfoService.queryEntityListByPage(bo, 1, 15);
            log.info(JsonUtil.getSucc4data(list));
            Assert.assertNotEquals(null, list);
        } catch (Exception e) {
            fail("分页查询设备异常");
        }
    }

    /**
     * Description: <br>
     * 
     * @author xubin<br>
     * @taskId <br>
     *         <br>
     */
    @Ignore
    @Test
    public void queryDeviceInfoByCacheTest() {
        log.info("查询缓存所有设备");
        sw.start("查询缓存所有设备");
        try {
            String appKey = "fa58f5306eb64ce094fe65fec6261587";
            String deviceCodes = "577984734685110272";
            List<DeviceCache> list = deviceInfoService.queryDeviceInfoByCache(appKey, deviceCodes);
            log.info(JsonUtil.getSucc4data(list));
            Assert.assertNotEquals(null, list);
        } catch (Exception e) {
            fail("查询缓存所有设备异常");
        }
    }
}
  • @Ignore 忽略测试方法
  • @Test 执行单元测试的方法

使用StopWatch可以统计单元测试类执行总时间以及每个@Test方法执行时间。

展开阅读全文
加载中

作者的其它热门文章

打赏
1
11 收藏
分享
打赏
2 评论
11 收藏
1
分享
返回顶部
顶部