1.导入maven依赖

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

过低版本如3.8.1版本不能用@标签

2.常用的注解

unit常用注解详细说明

Java注解((Annotation)的使用方法是@注解名 ,能通过简单的词语来实现一些功能。在junit中常用的注解有@Test、@Ignore、@BeforeClass、@AfterClass、@Before、@After、@Runwith、@Parameters

以下是相关的介绍和使用说明:

1).@Test

在junit3中,是通过对测试类和测试方法的命名来确定是否是测试,且所有的测试类必须继承junit的测试基类。

在junit4中,定义一个 测试方法变得简单很多,只需要在方法前加上@Test就行了。

注意:测试方法必须是public void,即公共、无返回数据。可以抛出异常。

2).@Ignore

有时候我们想暂时不运行某些测试方法\测试类,可以在方法前加此注解。在运行结果中,junit会统计忽略的用例数,来提醒你。

但是不建议经常这么做,因为这样的坏处时,容易忘记去更新这些测试方法,导致代码不够干净,用例遗漏。

3).@BeforeClass

当我们运行几个有关联的用例时,可能会在数据准备或其它前期准备中执行一些相同的命令,这个时候为了让代码更清晰,更少冗余,可以将公用的部分提取出来,放在一个方法里,并为这个方法注解@BeforeClass。意思是在测试类里所有用例运行之前,运行一次这个方法。例如创建数据库连接、读取文件等。

注意:方法名可以任意,但必须是public static void,即公开、静态、无返回。这个方法只会运行一次

4).@AfterClass

跟@BeforeClass对应,在测试类里所有用例运行之后,运行一次。用于处理一些测试后续工作,例如清理数据,恢复现场。

注意:同样必须是public static void,即公开、静态、无返回。这个方法只会运行一次。

5).@Before

与@BeforeClass的区别在于,@Before不止运行一次,它会在每个用例运行之前都运行一次。主要用于一些独立于用例之间的准备工作。比如两个用例都需要读取数据库里的用户A信息,但第一个用例会删除这个用户A,而第二个用例需要修改用户A。那么可以用@BeforeClass创建数据库连接。用@Before来插入一条用户A信息。

注意:必须是public void,不能为static。不止运行一次,根据用例数而定。

6).@After

与@Before对应。

7).@Runwith

首先要分清几个概念:测试方法、测试类、测试集、测试运行器。

其中测试方法就是用@Test注解的一些函数。测试类是包含一个或多个测试方法的一个**Test.java文件,测试集是一个suite,可能包含多个测试类。测试运行器则决定了用什么方式偏好去运行这些测试集/类/方法。

而@Runwith就是放在测试类名之前,用来确定这个类怎么运行的。也可以不标注,会使用默认运行器。

常见的运行器有:

1. @RunWith(Parameterized.class) 参数化运行器,配合@Parameters使用junit的参数化功能

2.@RunWith(Suite.class)

@SuiteClasses({ATest.class,BTest.class,CTest.class})

测试集运行器配合使用测试集功能

3.@RunWith(JUnit4.class)

junit4的默认运行器

4.@RunWith(JUnit38ClassRunner.class)

用于兼容junit3.8的运行器

5.一些其它运行器具备更多功能。例如@RunWith(SpringJUnit4ClassRunner.class)集成了spring的一些功能

8).@Parameters

用于使用参数化功能。

3.添加段言

assertEquals();

assertTrue();

需要import对应的类;

import static org.junit.Assert.assertTrue;

import static org.junit.Assert.assertEquals;

import static org.junit.Assert.*;

2018-06-08 11:00

4.利用junit4对springMVC所有层进行测试

package com.my.test;

import javax.annotation.Resource;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional; import com.my.service.TradeService; @RunWith(SpringJUnit4ClassRunner.class)//让测试运行于Spring环境
@ContextConfiguration({"classpath*:config/beans.xml","classpath*:/spring-mvc.xml"}) //引入Spring配置
public class TestJunit {
@Resource
private TradeService tradeService; @Test
@Transactional
public void testPagesNum() {
Assert.assertEquals("Pages num is not 2!", tradeService.getPagesNum(10), 2);
} }

 5.综合测试

package com.my.test;

import javax.annotation.Resource;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.my.service.TestService; @RunWith(SpringJUnit4ClassRunner.class) // 让测试运行于Spring环境
@ContextConfiguration({ "classpath*:config/beans.xml", "classpath*:/spring-mvc.xml" }) // 引入Spring配置
public class BaseTest { @Resource
TestService testService; @BeforeClass
public static void testBeforeClass() { System.out.println("BeforeClass");
} @Before
public void testBefore() { System.out.println("Before");
} @AfterClass
public static void testAfterClass() { System.out.println("AfterClass");
} @After
public void testAfter() { System.out.println("After");
} @Test
public void test1() { Assert.assertEquals("666", 11, 11);
} @Test
public void test2() { Assert.assertEquals("666", 11, 11);
} @Test
//让测试运行于Spring环境
public void testSpringMvc() {
System.out.println("====" + testService.getTestById(1).toString());
Assert.assertEquals("666", 11, 11);
} }

运行结果:

2019年2月14日 09:48:00

六.使用MockMvc测试Spring mvc Controller

概述

  对模块进行集成测试时,希望能够通过输入URL对Controller进行测试,如果通过启动服务器,建立http client进行测试,这样会使得测试变得很麻烦,比如,启动速度慢,测试验证不方便,依赖网络环境等,这样会导致测试无法进行,为了可以对Controller进行测试,可以通过引入MockMVC进行解决。

简介

  MockMvc实现了对Http请求的模拟,能够直接使用网络的形式,转换到Controller的调用,这样可以使得测试速度快、不依赖网络环境,而且提供了一套验证的工具,这样可以使得请求的验证统一而且很方便。

运行配置

用到的注解

  • RunWith(SpringJUnit4ClassRunner.class): 表示使用Spring Test组件进行单元测试;
  • WebAppConfiguration: 使用这个Annotate会在跑单元测试的时候真实的启一个web服务,然后开始调用Controller的Rest API,待单元测试跑完之后再将web服务停掉;
  • ContextConfiguration: 指定Bean的配置文件信息,可以有多种方式,这个例子使用的是文件路径形式,如果有多个配置文件,可以将括号中的信息配置为一个字符串数组来表示;

基本框架

/**
* 演示MockMVC使用
* @author zhanyongzhi
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:**web-config.xml")
@WebAppConfiguration
public class MockMvcTest {
private MockMvc mockMvc; @Autowired
private WebApplicationContext webApplicationContext; @Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
}

测试逻辑

  校验Controller处理之后,请求是否为成功状态,返回的内容是否包含了:"{'foo':'bar'}"字符串。

1 mockMvc调用perform,调用controller的业务处理逻辑
2 perform返回ResultActions,返回操作结果,通过ResultActions,提供了统一的验证方式。
3 使用StatusResultMatchers对请求结果进行验证
4 使用ContentResultMatchers对请求返回的内容进行验证

/**
* 演示MockMVC使用
* @author zhanyongzhi
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:**web-config.xml")
@WebAppConfiguration
public class MockMvcTest {
private MockMvc mockMvc; @Autowired
private WebApplicationContext webApplicationContext; @Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
} @Test
public void demo() throws Exception {
mockMvc.perform(get("/demo/test").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(content().json("{'foo':'bar'}"));
}
}

在 springboot中的使用

package com.my.study.test;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
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 com.my.study.controller.UserController; @RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
private MockMvc mvc; @Before
public void Setup() throws Exception{
mvc = MockMvcBuilders.standaloneSetup(new UserController()).build();
} @Test
public void getHello() throws Exception{
mvc.perform(MockMvcRequestBuilders.get("/user/test").accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn(); } }

完整代码在github中查看

参考

test mockmvc
integration testing
spring mvc unit test

2019年3月25日 08:00:29

 

1.Junit test使用的更多相关文章

  1. 记一个mvn奇怪错误: Archive for required library: 'D:/mvn/repos/junit/junit/3.8.1/junit-3.8.1.jar' in project 'xxx' cannot be read or is not a valid ZIP file

    我的maven 项目有一个红色感叹号, 而且Problems 存在 errors : Description Resource Path Location Type Archive for requi ...

  2. 「译」JUnit 5 系列:条件测试

    原文地址:http://blog.codefx.org/libraries/junit-5-conditions/ 原文日期:08, May, 2016 译文首发:Linesh 的博客:「译」JUni ...

  3. AndroidStudio — Error:Failed to resolve: junit:junit:4.12错误解决

    原博客:http://blog.csdn.net/u013443865/article/details/50243193 最近使用AndroidStudio出现以下问题: 解决:打开app下的buil ...

  4. 「译」JUnit 5 系列:环境搭建

    原文地址:http://blog.codefx.org/libraries/junit-5-setup/ 原文日期:15, Feb, 2016 译文首发:Linesh 的博客:环境搭建 我的 Gith ...

  5. [深入JUnit] 测试运行的入口

    阅读前提 了解JUnit 对JUnit的内部实现有兴趣 不妨看看[深入JUnit] @Before, @After, @Test的秘密] 代码版本: junit 4.12代码搜索工具: http:// ...

  6. 「译」JUnit 5 系列:扩展模型(Extension Model)

    原文地址:http://blog.codefx.org/design/architecture/junit-5-extension-model/ 原文日期:11, Apr, 2016 译文首发:Lin ...

  7. 「译」JUnit 5 系列:架构体系

    原文地址:http://blog.codefx.org/design/architecture/junit-5-architecture/ 原文日期:29, Mar, 2016 译文首发:Linesh ...

  8. 「译」JUnit 5 系列:基础入门

    原文地址:http://blog.codefx.org/libraries/junit-5-basics/ 原文日期:25, Feb, 2016 译文首发:Linesh 的博客:JUnit 5 系列: ...

  9. 新手入门JUnit单元测试

    首先将JUnit插件安装到Eclipse或myeclipse里面,编写完一个模块或者实体类的时候,直接右击,new一个JUnit项目,选择你想测试的实体类(模块),然后会自动生成一个类,这个类,我们将 ...

  10. [Android]使用自定义JUnit Rules、annotations和Resources进行单元测试(翻译)

    以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/5795091.html 使用自定义JUnit Rules.ann ...

随机推荐

  1. springboot-10-前端页面整合, thymeleaf, freemarker, jsp 模板使用

    springboot 中不建议使用jsp作为页面展示, 怎么使用可以看: http://412887952-qq-com.iteye.com/blog/2292471 关于什么是thymeleaf, ...

  2. 理解Linux内核之中断控制

    乍一看下边的Linux内核代码,貌似L3389有bug,于是我就绕有兴趣地阅读了一下local_irq_save/local_irq_restore的源代码. /* linux-4.14.12/mm/ ...

  3. Date类学习总结(Calendar Date 字符串 相互转换 格式化)

    Date类学习总结 1.计算某一月份的最大天数 Calendar time=Calendar.getInstance();time.clear();time.set(Calendar.YEAR,yea ...

  4. ARM的体系结构与编程系列博客——ARM体系变种

    ARM体系变种的简介 有人会很奇怪一件事情,ARM居然会变种,不会是基因突变了吧,呵呵,其实ARM变种通俗一点来讲呢,就是ARM突然具备了一种特定的功能!并非是基因突变哦!ARM是reboot好不好? ...

  5. [HNOI 2018]寻宝游戏

    Description 题库链接 给出 \(n\) 个 \(m\) 位的二进制数,在每一个二进制数间插入一个 & 或 | ,第 \(0\) 个数为 \(0\) , \(0,1\) 间也要插入符 ...

  6. [转载]常见的移动端H5页面开发遇到的坑和解决办法

    转过来,平时看看.虽然还有很多问题至今无解.比如:华为麒麟950的P8和meta打开我们的应用首页经常偶发白屏.!! 1.安卓浏览器看背景图片,有些设备会模糊. 用同等比例的图片在PC机上很清楚,但是 ...

  7. txt文本框设为密码模式后,后台(服务器端)设置不了值

    txt文本框设为密码模式后,因为安全问题,后台(服务器端)设置不了值,只有在前台(客户端)复制才能显示

  8. BASE64转文件下载

    你可以用HTML 5 注意:返回的文件数据必须是base 64编码的,因为您不能对二进制数据进行JSON编码 在我的AJAX我得到了如下的数据结构: <!DOCTYPE html> < ...

  9. 从以前的项目格式迁移到 VS2017 新项目格式

    以前的项目格式使用的是 csproj 的格式,但是 .net core 支持使用 project.json 格式的项目文件,后来还是决定不使用这个格式. VS2017 的项目格式更好读.更简单而且减少 ...

  10. jQuery ajax - getJSON() 用法实例

    实例 从 test.js 载入 JSON 数据并显示 JSON 数据中一个 name 字段数据: $.getJSON("test.js", function(json){ aler ...