1.Junit test使用
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(); } }
参考
test mockmvc
integration testing
spring mvc unit test
2019年3月25日 08:00:29
1.Junit test使用的更多相关文章
- 记一个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 ...
- 「译」JUnit 5 系列:条件测试
原文地址:http://blog.codefx.org/libraries/junit-5-conditions/ 原文日期:08, May, 2016 译文首发:Linesh 的博客:「译」JUni ...
- AndroidStudio — Error:Failed to resolve: junit:junit:4.12错误解决
原博客:http://blog.csdn.net/u013443865/article/details/50243193 最近使用AndroidStudio出现以下问题: 解决:打开app下的buil ...
- 「译」JUnit 5 系列:环境搭建
原文地址:http://blog.codefx.org/libraries/junit-5-setup/ 原文日期:15, Feb, 2016 译文首发:Linesh 的博客:环境搭建 我的 Gith ...
- [深入JUnit] 测试运行的入口
阅读前提 了解JUnit 对JUnit的内部实现有兴趣 不妨看看[深入JUnit] @Before, @After, @Test的秘密] 代码版本: junit 4.12代码搜索工具: http:// ...
- 「译」JUnit 5 系列:扩展模型(Extension Model)
原文地址:http://blog.codefx.org/design/architecture/junit-5-extension-model/ 原文日期:11, Apr, 2016 译文首发:Lin ...
- 「译」JUnit 5 系列:架构体系
原文地址:http://blog.codefx.org/design/architecture/junit-5-architecture/ 原文日期:29, Mar, 2016 译文首发:Linesh ...
- 「译」JUnit 5 系列:基础入门
原文地址:http://blog.codefx.org/libraries/junit-5-basics/ 原文日期:25, Feb, 2016 译文首发:Linesh 的博客:JUnit 5 系列: ...
- 新手入门JUnit单元测试
首先将JUnit插件安装到Eclipse或myeclipse里面,编写完一个模块或者实体类的时候,直接右击,new一个JUnit项目,选择你想测试的实体类(模块),然后会自动生成一个类,这个类,我们将 ...
- [Android]使用自定义JUnit Rules、annotations和Resources进行单元测试(翻译)
以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/5795091.html 使用自定义JUnit Rules.ann ...
随机推荐
- Amazon S3 功能介绍
一 .Amazon S3介绍 Amazon Simple Storage Service (Amazon S3) 是一种对象存储,它具有简单的 Web 服务接口,可用于在 Web 上的任何位置存储和检 ...
- ActiveMQ-在Centos7下安装和安全配置
环境准备: JDK1.8 ActiveMQ-5.11 Centos7 1.下载Linux版本的ActiveMQ: $ wget http://apache.fayea.com/activemq/5.1 ...
- kafka-spark streaming (一)
Kafka-spark streaming 1.安装包 kafka安装需要zookeeper.jdk. 官网下载最新的: https://kafka.apache.org/downloads http ...
- Golang 并发Groutine实例解读(一)
Go语言的并发和并行 不知道你有没有注意到一个现象,还是这段代码,如果我跑在两个goroutines里面的话: var quit chan int = make(chan int) func loop ...
- C# 枚举转字符串
有时候需要把枚举转字符串,那么如何把枚举转字符串? 枚举转字符串 假如需要把枚举转字符串,可以直接把他进行转换,请看代码 public enum Di { /// <summary> // ...
- 【JavaScript 从零开始】表达式和运算符(1)
原始表达式 最简单的表达式是"原始表达式"(primary expression).JavaScript中的原始表达式包含常量或直接量.关键字和变量. // 常量或直接量 1.23 ...
- 测试使用highlight.js的代码效果
---恢复内容开始--- C#代码 private void NextDateUpdate(DateTime dtt) { dtt.AddDays(); Response.Write("dt ...
- Java学习-jsp内置对象Session
- secureCRT的文件上传技巧
现在我们经常会习惯性的使用windows系统,但现在开发项目和维护中经常都在使用linux服务器,以为它的性能更强.更精简. 学习大数据的同志们和维护后端的同志们,推荐一下secureCRT软件,用起 ...
- 使用mybatis-generator生成自动代码
2019-02-22 配置文件: pom.xml 添加 dependency plugin 基于mybatis-plus <dependency> <groupId>o ...