单元测试最佳实战项目代码下载

1、单元测试框架对比了junit和TestNG的使用,推荐使用testNG

2、在mock层框架使用了easymock和powermock,推荐使用powermock,powermock可以访问私有的静态变量等

3、对于dao层数据库使用dbutil工具框架来导入模拟的测试数据

 

复制代码
/*
Navicat MySQL Data Transfer

Source Server         : 本地电脑2
Source Server Version : 50527
Source Host           : localhost:3306
Source Database       : test_junit

Target Server Type    : MYSQL
Target Server Version : 50527
File Encoding         : 65001

Date: 2018-06-25 10:13:14
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `t_user`
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id` int(111) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `nickname` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES ('1', 'admin343443', '123', '超级管理员');
复制代码

 

4、对于springmvc控制层的单元测试推荐使用MockMvc框架

复制代码
package com.atguigu.crud.test;

import java.util.List;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.atguigu.crud.bean.Employee;
import com.github.pagehelper.PageInfo;

/**
 * 使用Spring测试模块提供的测试请求功能,测试curd请求的正确性
 * Spring4测试的时候,需要servlet3.0的支持
 * @author lfy
 * 
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:applicationContext.xml",
        "classpath:dispatcher-servlet.xml" })
public class MvcTest {
    // 传入Springmvc的ioc
    @Autowired
    WebApplicationContext context;
    // 虚拟mvc请求,获取到处理结果。
    MockMvc mockMvc;

    @Before
    public void initMokcMvc() {
        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
    }

    @Test
    public void testPage() throws Exception {
        //模拟请求拿到返回值
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pn", "5"))
                .andReturn();

        //请求成功以后,请求域中会有pageInfo;我们可以取出pageInfo进行验证
        MockHttpServletRequest request = result.getRequest();
        Assert.assertNotNull(request);
        PageInfo pi = (PageInfo) request.getAttribute("aa");
        System.out.println("当前页码:"+pi.getPageNum());
        System.out.println("总页码:"+pi.getPages());
        System.out.println("总记录数:"+pi.getTotal());
        System.out.println("在页面需要连续显示的页码");
        int[] nums = pi.getNavigatepageNums();
        for (int i : nums) {
            System.out.print(" "+i);
        }
        
        //获取员工数据
        List<Employee> list = pi.getList();
        for (Employee employee : list) {
            System.out.println("ID:"+employee.getEmpId()+"==>Name:"+employee.getEmpName());
        }
        
    }
    //{"code":100,"msg":"业务操作成功","extend":{"pageInfo":{"pageNum":2,"pageSize":5,"size":5,"startRow":6,"endRow":10,"total":1001,"pages":201,"list":[{"empId":7,"empName":"a28595","gender":"M","email":"a28595@qq.com","dId":1,"department":{"deptId":1,"deptName":"研发部"}},{"empId":8,"empName":"d3fd26","gender":"M","email":"d3fd26@qq.com","dId":1,"department":{"deptId":1,"deptName":"研发部"}},{"empId":9,"empName":"2e04e7","gender":"M","email":"2e04e7@qq.com","dId":1,"department":{"deptId":1,"deptName":"研发部"}},{"empId":10,"empName":"7fa738","gender":"M","email":"7fa738@qq.com","dId":1,"department":{"deptId":1,"deptName":"研发部"}},{"empId":11,"empName":"d37ac9","gender":"M","email":"d37ac9@qq.com","dId":1,"department":{"deptId":1,"deptName":"研发部"}}],"prePage":1,"nextPage":3,"isFirstPage":false,"isLastPage":false,"hasPreviousPage":true,"hasNextPage":true,"navigatePages":5,"navigatepageNums":[1,2,3,4,5],"navigateFirstPage":1,"navigateLastPage":5,"firstPage":1,"lastPage":5}}}
    @Test
    public void testResult() throws Exception {
        //模拟请求拿到返回值
        //模拟请求拿到返回值
                MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pn", "5"))
                        .andReturn();
                 
                //请求成功以后,请求域中会有pageInfo;我们可以取出pageInfo进行验证
                MockHttpServletResponse response = result.getResponse();
                String string = response.getContentAsString();
                System.out.println(string);
                



     }
    
    @Test
    public void testFindUser() throws Exception {
        //模拟请求拿到返回值
        //模拟请求拿到返回值
        Employee employee2 = new Employee(2,"8727878","M","328989@qq.com",1);
                MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pn", "5"))
                        .andReturn();
             
                



     }
}
复制代码

 

代码的下载地址为

 链接:https://pan.baidu.com/s/1n09Io3LLqSIYV9O_GYZc6A 密码:13rq

posted on   luzhouxiaoshuai  阅读(319)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2017-06-25 c++教程网经典的c语音学习视频教程

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示