springboot-web进阶(四)——单元测试
2024-09-11 14:38:35
一、概述
基础知识,参考:https://www.cnblogs.com/ysw-go/p/5447056.html
二、springboot的单元测试
1.入门测试类
最重要的不要忘记类上面的依赖,以及类里面方法上的@Test(底层是jUnit)
package com.example.demo; import com.example.demo.service.GirlService;
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; /**
* GirlService测试类
*
* @author zcc ON 2018/2/9
**/
@RunWith(SpringRunner.class)
@SpringBootTest
public class GirlServiceTest { @Autowired
private GirlService girlService;
@Test
public void findOneTest() {
Assert.assertEquals(new Integer(20), girlService.findOne(4).getAge());
}
}
这样,就可以看到相关结果了:
// 为了高大上一点,请不要再使用小白式的sout了,多使用断言.
2.使用IDEA自动生成测试类
例如还是测试上面的service里的findOne,则通过在方法上右击->Goto->Test
3.controller的API单元测试
同样,在方法上右击,Goto->Test,得到测试类
package com.example.demo.controller; import com.example.demo.SpringbootDemoApplicationTests;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import static org.junit.Assert.*; @AutoConfigureMockMvc
public class GirlControllerTest extends SpringbootDemoApplicationTests { @Autowired
private MockMvc mvc;
@Test
public void getList() throws Exception {
// 测试状态码
mvc.perform(MockMvcRequestBuilders.get("/girls"))
.andExpect(MockMvcResultMatchers.status().isOk());
} }
使用单元测试还有一个用处是在打包是会自动跑单元测试,并会给出测试结果,失败时将会报ERROR!
还有其他测试选项,例如测试.content.string("abc"来测试返回内容),完整的API,参考:这里
最新文章
- 设置line-height:1.5和line-height:150%或者line-height:150px的区别
- Mac git提交步骤小记
- NPOI教程
- extjs 常见的小问题
- 挣值管理(EVT)
- C# mvc--EF引用程序集 和EDMX中相关的文件说明
- WinScp上传和下载
- A Full Hardware Guide to Deep Learning
- 深入分析:微信小程序与H5的区别
- eslint 的基本配置介绍
- Cygwin,一个提供linux命令行体验的Windows命令行工具
- mysql8.0.11绿色版安装教程
- 转 国内的go get问题的解决
- debug makefile 及 lint 软件质量软件
- wps表格开发C#
- ms sql server读取xml文件存储过程-sp_xml_preparedocument
- Python实现京东自动登录
- python 基础数据类型之list
- 高并发应对:淘宝CDN缓存服务器部署探秘
- **利用列表和super实现有序字典
热门文章
- java基础(八) 深入解析常量池与装拆箱机制
- SQLServer中DataLength()和Len()两内置函数的区别
- REST Framework组件的解析源码
- ASP.NET MVC 5 开发环境配置
- October 07th 2017 Week 40th Saturday
- D:\hunting2014\小题目\字符串倒序
- 18年10月31日 NOIP模拟赛
- Android混合式开发(Hybrid)
- Undefined function or method 'deploywhich' for input arguments of type 'char'
- springboot 配置jpa启动报Error processing condition on org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration.pageableCustomizer