跳至主要內容

junit单元测试

李鹏军...大约 1 分钟开源教程文档

junit单元测试

该项目已集成基于spring的junit单元测试,方便开发人员进行功能测试。

单元测试代码结构

/img/start/06/img.png
/img/start/06/img.png

实现原理

package com.platform;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;

/**
 * 基于spring的单元测试基类
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2018-07-09 10:06:23
 */
@ContextConfiguration(locations = {"classpath:applicationContext-test.xml"})
public class BaseSpringTestCase extends AbstractJUnit4SpringContextTests {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 获取Logger
     */
    public Logger getLogger() {
        return logger;
    }
}

使用@contextConfiguration注解引入spring的配置文件,如果有多个配置文件用逗号隔开。

使用方法

继承BaseSpringTestCase类就可以开发测试类。用于测试的配置文件已经扫描项目中的bean,所以可以直接使用项目中的service进行测试,demo如下:

package com.platform.controller;

import com.platform.BaseSpringTestCase;
import com.platform.entity.SysUserEntity;
import com.platform.service.SysUserService;
import com.platform.service.TestSysUserService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会员测试
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2018-07-09 10:13:43
 */
public class TestSysUserController extends BaseSpringTestCase {
    @Autowired
    TestSysUserService testSysUserService;
    @Autowired
    SysUserService sysUserService;

    /**
     * 使用测试类
     */
    @Test
    public void queryTestSysUserList() {
        Map<String, Object> params = new HashMap<>();
        List<SysUserEntity> list = testSysUserService.queryList(params);
        if (list != null && list.size() != 0) {
            for (SysUserEntity userEntity : list) {
                logger.info("username:" + userEntity.getUsername() + ";mobile:" + userEntity.getMobile());
            }
        }
    }

    /**
     * 使用项目中的service
     */
    @Test
    public void querySysUserList() {
        Map<String, Object> params = new HashMap<>();
        List<SysUserEntity> list = sysUserService.queryList(params);
        if (list != null && list.size() != 0) {
            for (SysUserEntity userEntity : list) {
                logger.info("username:" + userEntity.getUsername() + ";mobile:" + userEntity.getMobile());
            }
        }
    }
}