当前位置: 首页 > news >正文

如何编写单元测试

一、前言知识

1.开发过程

需求分析->设计->开发->测试->上线

2.测试种类

单元测试(测试模块编码)、黑盒测试(测试功能是否满足需求)、白盒测试(测试程序内部的逻辑结构)、回归测试(提出的缺陷进行二次验证)、集成测试(测试主要的业务功能及模块间的整合性)、系统测试(测试整个产品系统)

二、单元测试的使用

1.引入相关依赖

<!-- 单元测试的依赖-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

2.编写单元测试方法

断言:判断程序结果是否符合预期 TestCase.assertXXX

package net.xdclass.demoproject;


import junit.framework.TestCase;
import net.xdclass.demoproject.domain.Video;
import net.xdclass.demoproject.service.VideoService;
import org.junit.After;
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.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
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.result.MockMvcResultMatchers;

import java.nio.charset.Charset;
import java.util.List;

//1.配置
@RunWith(SpringRunner.class)  //底层用junit  SpringJUnit4ClassRunner
@SpringBootTest(classes={DemoProjectApplication.class})//启动整个springboot工程
@AutoConfigureMockMvc
public class VideoTest {


    @Autowired//会自动将VideoService对象注入到VideoTest对象中,相当于new VideoService()
    private VideoService videoService;


//2.常用注解的使用
    @Before//在测试用例执行前执行
    public void testOne(){

        System.out.println("这个是测试 before");
    }



    @Test//测试用例
    public void testVideoList(){

        List<Video> videoList = videoService.listVideo();

 //判断videoList的大小是否大于0,如果大于0,则测试通过,如果小于0,则测试失败
        TestCase.assertTrue(videoList.size()>0);

    }

    @After//在测试用例执行后执行
    public void testThree(){

        System.out.println("这个是测试 after");
    }

}

三、单元测试的应用

1.测试controller层登录方法

UserTest

package net.xdclass.demoproject;


import junit.framework.TestCase;
import net.xdclass.demoproject.controller.UserController;
import net.xdclass.demoproject.domain.User;
import net.xdclass.demoproject.utils.JsonData;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)  //底层用junit  SpringJUnit4ClassRunner
@SpringBootTest(classes={DemoProjectApplication.class})//启动整个springboot工程
public class UserTest {

    @Autowired
    private UserController userController;

    @Test
    public void loginTest(){

        //模拟前端传递过来的参数
        User user = new User();
        user.setUsername("jack");
        user.setPwd("1234");

        //调用controller的login方法
        JsonData jsonData  = userController.login(user);

        //打印返回的json数据
        System.out.println(jsonData.toString());

        //断言
        TestCase.assertEquals(0,jsonData.getCode());

    }
}

2.测试service层视频列表

VideoTest

package net.xdclass.demoproject;


import junit.framework.TestCase;
import net.xdclass.demoproject.domain.Video;
import net.xdclass.demoproject.service.VideoService;
import org.junit.After;
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.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
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.result.MockMvcResultMatchers;

import java.nio.charset.Charset;
import java.util.List;

@RunWith(SpringRunner.class)  //底层用junit  SpringJUnit4ClassRunner
@SpringBootTest(classes={DemoProjectApplication.class})//启动整个springboot工程
public class VideoTest {

    @Autowired//会自动将VideoService对象注入到VideoTest对象中,相当于new VideoService()
    private VideoService videoService;


    @Test//测试用例
    public void testVideoList(){

        List<Video> videoList = videoService.listVideo();

        //判断videoList的大小是否大于0,如果大于0,则测试通过,如果小于0,则测试失败
        TestCase.assertTrue(videoList.size()>0);

    }

}

3.测试对外提供的接口

 VideoTest

package net.xdclass.demoproject;


import junit.framework.TestCase;
import net.xdclass.demoproject.domain.Video;
import net.xdclass.demoproject.service.VideoService;
import org.junit.After;
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.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
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.result.MockMvcResultMatchers;

import java.nio.charset.Charset;
import java.util.List;

@RunWith(SpringRunner.class)  //底层用junit  SpringJUnit4ClassRunner
@SpringBootTest(classes={DemoProjectApplication.class})//启动整个springboot工程
@AutoConfigureMockMvc//自动注入MockMvc对象,用于模拟请求
public class VideoTest {


    @Autowired//会自动将VideoService对象注入到VideoTest对象中,相当于new VideoService()
    private VideoService videoService;

    @Autowired
    private MockMvc mockMvc;//模拟请求


    @Test//测试用例
    public void testVideoListApi()throws Exception{

        //模拟请求:会返回一个MvcResult对象,里面包含了响应的状态码,响应的内容
       MvcResult mvcResult =  mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/pub/video/list"))//访问接口的地址
                .andExpect(MockMvcResultMatchers.status().isOk()).andReturn();

       int status = mvcResult.getResponse().getStatus();//获取响应的状态码

       System.out.println(status);

               // 使用下面这个,增加编码说明,就不会乱码打印
        String result = mvcResult.getResponse().getContentAsString(Charset.forName("utf-8"));

       System.out.println(result);

    }
}

四、小结 

          单元测试的实质就是通过加入测试工具依赖,然后使用注释和断言来配合验证不同取值下功能模块的输出结果与预期结果是否一致。

 

相关文章:

  • UE4学习笔记 FPS游戏制作26 UE中的UI
  • Rust 面向对象
  • AI笔记工具如何改变传统笔记方式:从手写到无纸化的转变
  • 模型压缩与迁移:基于蒸馏技术的实战教程
  • 本地化智能运维助手:基于 LangChain 数据增强 和 DeepSeek-R1 的K8s运维文档检索与问答系统 Demo
  • 【C++游戏引擎开发】《线性代数》(2):矩阵加减法与SIMD集成
  • JAVA学习笔记——第十二章 异常
  • 【Mysql】深入剖析 MySQL 死锁问题及应对策略
  • 项目-苍穹外卖(十四) Spring Task+订单状态定时处理
  • Langchain4j实现本地RAG和联网查询
  • 网络中常用协议
  • 【机器学习】基础知识
  • Ubuntu Linux安装PyQt5并配置Qt Designer
  • 面试记录3
  • IoT平台实时监测机器人状态的实现方案
  • Ubuntu24.04 离线安装 MySQL8.0.41
  • 零基础如何学习自动化测试
  • RAGFlow部署时遇到的mysql unhealthy问题解决方案汇总
  • 108.在 Vue 3 中使用 OpenLayers 加载 XYZ 地图的示例
  • [微信小程序]对接sse接口
  • python创建wordpress/如何优化网站
  • 网站建设好销售吗/关键词检测
  • 云服务器怎么样做网站/优化大师官网登录入口
  • 安徽合肥中国建设银行网站首页/长沙企业关键词优化哪家好
  • 馆陶网站建设费用/搜索引擎广告
  • 淘客网站备案/谷歌海外推广怎么做