一.Service层单元测试:

代码如下:

package com.dudu.service;import com.dudu.domain.LearnResource;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;import static org.hamcrest.CoreMatchers.*;

@RunWith(SpringRunner.class)@SpringBootTestpublic class LearnServiceTest {

    @Autowired    private LearnService learnService;

    @Test    public void getLearn(){        LearnResource learnResource=learnService.selectByKey(1001L);        Assert.assertThat(learnResource.getAuthor(),is("博客园"));    }}就是最简单的单元测试写法,顶部只要@RunWith(SpringRunner.class)SpringBootTest即可,想要执行的时候,鼠标放在对应的方法,右键选择run该方法即可。

二.Controller层单元测试

Controller类:

package com.dudu.controller;

/**  * 教程页面 */@Controller@RequestMapping("/learn")public class LearnController  extends AbstractController{

    @Autowired    private LearnService learnService;

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

    @RequestMapping("")    public String learn(Model model){        model.addAttribute("ctx", getContextPath()+"/");        return "learn-resource";    }

    /**     * 查询教程列表     * @param page     * @return     */    @RequestMapping(value = "/queryLeanList",method = RequestMethod.POST)    @ResponseBody    public AjaxObject queryLearnList(Page<LeanQueryLeanListReq> page){        List<LearnResource> learnList=learnService.queryLearnResouceList(page);        PageInfo<LearnResource> pageInfo =new PageInfo<LearnResource>(learnList);        return AjaxObject.ok().put("page", pageInfo);    }

    /**     * 新添教程     * @param learn     */    @RequestMapping(value = "/add",method = RequestMethod.POST)    @ResponseBody    public AjaxObject addLearn(@RequestBody LearnResource learn){        learnService.save(learn);        return AjaxObject.ok();    }

    /**     * 修改教程     * @param learn     */    @RequestMapping(value = "/update",method = RequestMethod.POST)    @ResponseBody    public AjaxObject updateLearn(@RequestBody LearnResource learn){        learnService.updateNotNull(learn);        return AjaxObject.ok();    }

    /**     * 删除教程     * @param ids     */    @RequestMapping(value="/delete",method = RequestMethod.POST)    @ResponseBody    public AjaxObject deleteLearn(@RequestBody Long[] ids){        learnService.deleteBatch(ids);        return AjaxObject.ok();    }

    /**     * 获取教程     * @param id     */    @RequestMapping(value="/resource/{id}",method = RequestMethod.GET)    @ResponseBody    public LearnResource qryLearn(@PathVariable(value = "id") Long id){       LearnResource lean= learnService.selectByKey(id);        return lean;    }}
Controller的测试类:

代码如下:
package com.dudu.controller;

import com.dudu.domain.User;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.context.SpringBootTest;import org.springframework.http.MediaType;import org.springframework.mock.web.MockHttpSession;import org.springframework.test.context.junit4.SpringRunner;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;import org.springframework.test.web.servlet.result.MockMvcResultHandlers;import org.springframework.test.web.servlet.result.MockMvcResultMatchers;import org.springframework.test.web.servlet.setup.MockMvcBuilders;import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)@SpringBootTestpublic class LearnControllerTest {

    @Autowired    private WebApplicationContext context;

    private MockMvc mvc;

    private MockHttpSession session;

    @Before    public void setupMockMvc(){        mvc = MockMvcBuilders.webAppContextSetup(wac).build(); //初始化MockMvc对象        session = new MockHttpSession();        User user =new User("root","root");        session.setAttribute("user",user); //拦截器那边会判断用户是否登录,所以这里注入一个用户    }

    /**     * 新增教程测试用例     * @throws Exception     */    @Test    public void addLearn() throws Exception{        String json="{\"author\":\"HAHAHAA\",\"title\":\"Spring\",\"url\":\"http://tengj.top/\"}";        mvc.perform(MockMvcRequestBuilders.post("/learn/add")                    .accept(MediaType.APPLICATION_JSON_UTF8)                    .content(json.getBytes()) //传json参数                    .session(session)            )           .andExpect(MockMvcResultMatchers.status().isOk())           .andDo(MockMvcResultHandlers.print());    }

    /**     * 获取教程测试用例     * @throws Exception     */    @Test    public void qryLearn() throws Exception {        mvc.perform(MockMvcRequestBuilders.get("/learn/resource/1001")                    .contentType(MediaType.APPLICATION_JSON_UTF8)                    .accept(MediaType.APPLICATION_JSON_UTF8)                    .session(session)            )           .andExpect(MockMvcResultMatchers.status().isOk())           .andExpect(MockMvcResultMatchers.jsonPath("$.author").value("嘟嘟MD独立博客"))           .andExpect(MockMvcResultMatchers.jsonPath("$.title").value("Spring Boot干货系列"))           .andDo(MockMvcResultHandlers.print());    }

    /**     * 修改教程测试用例     * @throws Exception     */    @Test    public void updateLearn() throws Exception{        String json="{\"author\":\"测试修改\",\"id\":1031,\"title\":\"Spring Boot干货系列\",\"url\":\"http://tengj.top/\"}";        mvc.perform(MockMvcRequestBuilders.post("/learn/update")                .accept(MediaType.APPLICATION_JSON_UTF8)                .content(json.getBytes())//传json参数                .session(session)        )                .andExpect(MockMvcResultMatchers.status().isOk())                .andDo(MockMvcResultHandlers.print());    }

    /**     * 删除教程测试用例     * @throws Exception     */    @Test    public void deleteLearn() throws Exception{        String json="[1031]";        mvc.perform(MockMvcRequestBuilders.post("/learn/delete")                .accept(MediaType.APPLICATION_JSON_UTF8)                .content(json.getBytes())//传json参数                .session(session)        )                .andExpect(MockMvcResultMatchers.status().isOk())                .andDo(MockMvcResultHandlers.print());    }

}

三.新断言assertThat使用

 基本语法:assertThat( [value], [matcher statement] );
  • value 是接下来想要测试的变量值;
  • matcher statement 是使用 Hamcrest 匹配符来表达的对前面变量所期望的值的声明,如果 value 值与 matcher statement 所表达的期望值相符,则测试成功,否则测试失败

使用例子:

字符相关匹配符/**equalTo匹配符断言被测的testedValue等于expectedValue,* equalTo可以断言数值之间,字符串之间和对象之间是否相等,相当于Object的equals方法*/assertThat(testedValue, equalTo(expectedValue));/**equalToIgnoringCase匹配符断言被测的字符串testedString*在忽略大小写的情况下等于expectedString*/assertThat(testedString, equalToIgnoringCase(expectedString));/**equalToIgnoringWhiteSpace匹配符断言被测的字符串testedString*在忽略头尾的任意个空格的情况下等于expectedString,*注意:字符串中的空格不能被忽略*/assertThat(testedString, equalToIgnoringWhiteSpace(expectedString);/**containsString匹配符断言被测的字符串testedString包含子字符串subString**/assertThat(testedString, containsString(subString) );/**endsWith匹配符断言被测的字符串testedString以子字符串suffix结尾*/assertThat(testedString, endsWith(suffix));/**startsWith匹配符断言被测的字符串testedString以子字符串prefix开始*/assertThat(testedString, startsWith(prefix));一般匹配符/**nullValue()匹配符断言被测object的值为null*/assertThat(object,nullValue());/**notNullValue()匹配符断言被测object的值不为null*/assertThat(object,notNullValue());/**is匹配符断言被测的object等于后面给出匹配表达式*/assertThat(testedString, is(equalTo(expectedValue)));/**is匹配符简写应用之一,is(equalTo(x))的简写,断言testedValue等于expectedValue*/assertThat(testedValue, is(expectedValue));/**is匹配符简写应用之二,is(instanceOf(SomeClass.class))的简写,*断言testedObject为Cheddar的实例*/assertThat(testedObject, is(Cheddar.class));/**not匹配符和is匹配符正好相反,断言被测的object不等于后面给出的object*/assertThat(testedString, not(expectedString));/**allOf匹配符断言符合所有条件,相当于“与”(&&)*/assertThat(testedNumber, allOf( greaterThan(8), lessThan(16) ) );/**anyOf匹配符断言符合条件之一,相当于“或”(||)*/assertThat(testedNumber, anyOf( greaterThan(16), lessThan(8) ) );数值相关匹配符/**closeTo匹配符断言被测的浮点型数testedDouble在20.0¡À0.5范围之内*/assertThat(testedDouble, closeTo( 20.0, 0.5 ));/**greaterThan匹配符断言被测的数值testedNumber大于16.0*/assertThat(testedNumber, greaterThan(16.0));/** lessThan匹配符断言被测的数值testedNumber小于16.0*/assertThat(testedNumber, lessThan (16.0));/** greaterThanOrEqualTo匹配符断言被测的数值testedNumber大于等于16.0*/assertThat(testedNumber, greaterThanOrEqualTo (16.0));/** lessThanOrEqualTo匹配符断言被测的testedNumber小于等于16.0*/assertThat(testedNumber, lessThanOrEqualTo (16.0));集合相关匹配符/**hasEntry匹配符断言被测的Map对象mapObject含有一个键值为"key"对应元素值为"value"的Entry项*/assertThat(mapObject, hasEntry("key", "value" ) );/**hasItem匹配符表明被测的迭代对象iterableObject含有元素element项则测试通过*/assertThat(iterableObject, hasItem (element));/** hasKey匹配符断言被测的Map对象mapObject含有键值“key”*/assertThat(mapObject, hasKey ("key"));/** hasValue匹配符断言被测的Map对象mapObject含有元素值value*/assertThat(mapObject, hasValue(value));
 

Spring Boot使用单元测试的更多相关文章

  1. Spring Boot学习——单元测试

    本随笔记录使用Spring Boot进行单元测试,主要是Service和API(Controller)进行单元测试. 一.Service单元测试 选择要测试的service类的方法,使用idea自动创 ...

  2. Spring Boot干货系列:(十二)Spring Boot使用单元测试(转)

    前言这次来介绍下Spring Boot中对单元测试的整合使用,本篇会通过以下4点来介绍,基本满足日常需求 Service层单元测试 Controller层单元测试 新断言assertThat使用 单元 ...

  3. Spring Boot 的单元测试

    Spring Boot 的单元测试 引入依赖 testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-tes ...

  4. 学习 Spring Boot:(二十九)Spring Boot Junit 单元测试

    前言 JUnit 是一个回归测试框架,被开发者用于实施对应用程序的单元测试,加快程序编制速度,同时提高编码的质量. JUnit 测试框架具有以下重要特性: 测试工具 测试套件 测试运行器 测试分类 了 ...

  5. Spring Boot Mock单元测试学习总结

    单元测试的方法有很多种,比如使用Postman.SoapUI等工具测试,当然,这里的测试,主要使用的是基于RESTful风格的SpringMVC的测试,我们可以测试完整的Spring MVC流程,即从 ...

  6. Spring Boot 的单元测试和集成测试

    学习如何使用本教程中提供的工具,并在 Spring Boot 环境中编写单元测试和集成测试. 1. 概览 本文中,我们将了解如何编写单元测试并将其集成在 Spring Boot 环境中.你可在网上找到 ...

  7. Spring Boot 2 单元测试

    开发环境:IntelliJ IDEA 2019.2.2Spring Boot版本:2.1.8 IDEA新建一个Spring Boot项目后,pom.xml默认包含了Web应用和单元测试两个依赖包.如下 ...

  8. (27)Spring Boot Junit单元测试【从零开始学Spring Boot】

    Junit这种老技术,现在又拿出来说,不为别的,某种程度上来说,更是为了要说明它在项目中的重要性. 那么先简单说一下为什么要写测试用例 1. 可以避免测试点的遗漏,为了更好的进行测试,可以提高测试效率 ...

  9. (转)Spring Boot Junit单元测试

    场景:在项目开发中要测试springboot工程中一个几个dao和service的功能是否正常,初期是在web工程中进行要素的录入,工作量太大.使用该单元测试大大减小了工作强度. Junit这种老技术 ...

随机推荐

  1. 漏洞复现——httpd换行解析漏洞

    漏洞原理: 在解析php文件时,1.php\x0A这种格式的文件将会被认为php文件解析,进而可以绕过一些服务器的安全策略. 漏洞版本: 2.4.0~2.4.29 漏洞复现: 复现该漏洞是利用dock ...

  2. JavaScript 复杂判断的更优雅写法

    我们编写js代码时经常遇到复杂逻辑判断的情况,通常大家可以用if/else或者switch来实现多个条件判断,但这样会有个问题,随着逻辑复杂度的增加,代码中的if/else/switch会变得越来越臃 ...

  3. 第9天【btrfs文件系统、压缩工具及for语句、程序包管理】

    btrfs文件系统管理与应用(01)_recv halt centos7: mkfs.btrfs命令: -L:指定卷标 -m:元数据 -d:指定数据存储的类型,raid1.5.10.single 实验 ...

  4. xftp免费版使用

    转自https://www.jb51.net/softs/621774.html

  5. .net core部署到Ubuntu碰到的问题

    数据库连接的时候,会报错“MySql.Data.MySqlClient.MySqlException:“The host localhost does not support SSL connecti ...

  6. 64位win7连接ACCESS报错“Microsoft.Jet.OLEDB.4.0”问题

    本人开发了桌面软件,关于事务提醒,自己一直在用,很喜欢,但是在64位win7上无法运行,网上说多种方法,都觉得麻烦.后来自己在vs2012下编译成x86版本,结果可以运行在64位win7下了. 原来如 ...

  7. java 创建string对象机制 字符串缓冲池 字符串拼接机制 字符串中intern()方法

    字符串常量池:字符串常量池在方法区中 为了优化空间,为了减少在JVM中创建的字符串的数量,字符串类维护了一个字符串池,每当代码创建字符串常量时,JVM会首先检查字符串常量池.如果字符串已经存在池中,就 ...

  8. python_day4

    昨日回顾:     1. 整型         python2  有长整型        python3  没有长整型     2.布尔值        转换     3.字符串详解        下 ...

  9. [Leetcode 90]求含有重复数的子集 Subset II

    [题目] Given a collection of integers that might contain duplicates, nums, return all possible subsets ...

  10. linux c++ curl 根据IP地址获得当前网络的所在的地理位置

    注意: 可能每个电脑的默认中文编码格式不同,有时会出现乱码,需要对返回内容进行编码转换,或者换成可指定编码格式的接口.如  搜狐IP地址查询接口(可设置编码):http://pv.sohu.com/c ...