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. Spring Security构建Rest服务-1400-授权

    安全分为 认证和授权,前边讲的都是认证,现在说授权. 前端业务系统的权限简单些,一般只区分是否登录,复杂点的还会区分 VIP用户等简单的角色,权限规则基本不变. 后台系统比较复杂,角色众多,权限随着业 ...

  2. Spring Security构建Rest服务-0702-短信验证码登录

    先来看下 Spring Security密码登录大概流程,模拟这个流程,开发短信登录流程 1,密码登录请求发送给过滤器 UsernamePasswordAuthenticationFilter 2,过 ...

  3. javascript中的浅拷贝和深拷贝 分类: JavaScript 2015-05-07 15:29 831人阅读 评论(1) 收藏

    1.js对象浅拷贝 简单的赋值就是浅拷贝.因为对象和数组在赋值的时候都是引用传递.赋值的时候只是传递一个指针. 看下面的实例代码: var a = [1,2,3]; var b =a ; var te ...

  4. gcc 编译问题

    一般情况一句话即可: gcc -o fuck fuck.c ./fuck 直接运行了 问题 1. 报错 ld 未找到 此时,gcc编译得分布来,并且指定特定的ld gcc -c  1.c //会在目录 ...

  5. 关于Item

    0.Item The base class of all items, which implements default behavior. 项(Item)代表一个字节码中可以寻址的实体,有许多种类的 ...

  6. Nginx的进程

    传统上基于进程或线程模型架构的web服务通过每进程或每线程处理并发连接请求,这势必会在网络和I/O操作时产生阻塞,其另一个必然结果则是对内存或CPU的利用率低下.生成一个新的进程/线程需要事先备好其运 ...

  7. PM2怎么开启ES6?

    node版本v6.14.2,无论是用配置文件 { "apps": [{ "name": "server", "script&quo ...

  8. Class.forName(),Class.forName().newInstance() ,New ,类名.class,,class.forName(),,getClass()

       在Java开发特别是数据库开发中,经常会用到Class.forName( )这个方法.通过查询Java Documentation我们会发现使用Class.forName( )静态方法的目的是为 ...

  9. java.util.Collection源码分析和深度讲解

    写在开头 java.util.Collection 作为Java开发最常用的接口之一,我们经常使用,今天我带大家一起研究一下Collection接口,希望对大家以后的编程以及系统设计能有所帮助,本文所 ...

  10. [BZOJ 2655]calc

    Description 题库链接 给出 \(A,n,p\) ,让你在模 \(p\) 意义下求所有序列 \(a\) 满足"长度为 \(n\) 且 \(a_i\in[1,A]\) ,并且对于 \ ...