如何用JUnit单元测试List

问题

JUnit测试List时差强人意。

解法

引入依赖

hamcrest-library包含许多有用方法来测试List数据类型。

<dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope><exclusions><exclusion><groupId>org.hamcrest</groupId><artifactId>hamcrest-core</artifactId></exclusion></exclusions></dependency><!-- This will get hamcrest-core automatically --><dependency><groupId>org.hamcrest</groupId><artifactId>hamcrest-library</artifactId><version>1.3</version><scope>test</scope></dependency>...

断言含有String的List

查阅org.hamcrest.collection包,它包含许多有用方法来测试CollectionList

import org.junit.Test;import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;import org.hamcrest.collection.IsEmptyCollection;import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.hamcrest.MatcherAssert.assertThat;public class StringListTest {@Testpublic void test() {List<String> actual = Arrays.asList("a", "b", "c");List<String> expected = Arrays.asList("a", "b", "c");// All passed / true// 1. Test equal.assertThat(actual, is(expected));// 2. If List has this value?assertThat(actual, hasItems("b"));// 3. Check List SizeassertThat(actual, hasSize(3));assertThat(actual.size(), is(3));// 4. List order// Ensure Correct orderassertThat(actual, contains("a", "b", "c"));// Can be any orderassertThat(actual, containsInAnyOrder("c", "b", "a"));// 5. check empty listassertThat(actual, not(IsEmptyCollection.empty()));assertThat(new ArrayList<>(), IsEmptyCollection.empty());}
}

断言含有Integer的List

查阅org.hamcrest.number包,它包含许多有用方法来测试数目。

import org.junit.Test;import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;import org.hamcrest.collection.IsEmptyCollection;import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
import static org.hamcrest.number.OrderingComparison.lessThan;import static org.hamcrest.MatcherAssert.assertThat;public class IntegerListTest {@Testpublic void test() {List<Integer> actual = Arrays.asList(1, 2, 3, 4, 5);List<Integer> expected = Arrays.asList(1, 2, 3, 4, 5);// All passed / true// 1. Test equal.assertThat(actual, is(expected));// 2. Check List has this valueassertThat(actual, hasItems(2));// 3. Check List SizeassertThat(actual, hasSize(5));assertThat(actual.size(), is(5));// 4. List order// Ensure Correct orderassertThat(actual, contains(1, 2, 3, 4, 5));// Can be any orderassertThat(actual, containsInAnyOrder(5, 4, 3, 2, 1));// 5. check empty listassertThat(actual, not(IsEmptyCollection.empty()));assertThat(new ArrayList<>(), IsEmptyCollection.empty());// 6. Test numeric comparisonsassertThat(actual, everyItem(greaterThanOrEqualTo(1)));assertThat(actual, everyItem(lessThan(10)));}}

Note
Both org.hamcrest.collection and org.hamcrest.number are belong to hamcrest-library

断言含有Object的List

一个POJO类:

import java.util.Objects;public class Fruit {public Fruit(String name, int qty) {this.name = name;this.qty = qty;}private String name;private int qty;public int getQty() {return qty;}public void setQty(int qty) {this.qty = qty;}public String getName() {return name;}public void setName(String name) {this.name = name;}// Test equal, override equals() and hashCode()@Overridepublic boolean equals(Object o) {if (this == o)return true;if (o == null || getClass() != o.getClass())return false;Fruit fruit = (Fruit) o;return qty == fruit.qty && Objects.equals(name, fruit.name);}@Overridepublic int hashCode() {return Objects.hash(name, qty);}
}

测试类:

import org.junit.Test;import java.util.Arrays;
import java.util.List;import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.junit.Assert.assertThat;public class ObjectListTest {@Test@SuppressWarnings("unchecked")public void test() {List<Fruit> list = Arrays.asList(new Fruit("Banana", 99), new Fruit("Apple", 20));// Test equalsassertThat(list, hasItems(new Fruit("Banana", 99), //new Fruit("Apple", 20)));assertThat(list, containsInAnyOrder(new Fruit("Apple", 20), // new Fruit("Banana", 99)));// Test class property, and its valueassertThat(list, containsInAnyOrder(hasProperty("name", is("Apple")), hasProperty("name", is("Banana"))));}
}

参考

  1. JUnit – How to test a List
  2. Hamcrest official site

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/445793.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java数据包解析_请教http请求数据包如何解析 重组

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼下面是我捕获到的请求报文片段dst_ip:/121.52.228.134ack:trueack_num:3064957366date:POST /messagebroker/amf HTTP/1.1Host: s16.xxhzw.game.yy.comUser-Agent: Mozilla/5.0 (Windows NT 5.1; rv:13.0) Gecko/20100101 Firefox/…

webqq java_WebQQ登录详解

第二次登录请求方式:POST地址:http://d.web2.qq.com/channel/login2POST正文:r%7B%22status%22%3A%22online%22%2C%22ptwebqq%22%3A%22{0}%22%2C%22passwd_sig%22%3A%22%22%2C%22clientid%22%3A%22{1}%22%2C%22  psessionid%22%3Anull%7D&clientid{2}&psessionidnull…

LeetCode - Easy - 155. Min Stack

Topic StackDesign Description https://leetcode.com/problems/min-stack/ Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) – Push element x onto stack.pop() – Removes the element on top of the st…

java judgefilecode_VScode出现无法打开“X”: 找不到文件(file:///XXXX) 的解决办法

如标题&#xff0c;被这个问题整了好长时间了&#xff0c;调试的时候如果有语法错误只能显示相应的的行数&#xff0c;没有办法定位到出错的行数上。(由于用处不是很大并且没有找到解决办法&#xff0c;所以就一直放着没管23333)直到最近看到一位大佬的解决办(重写正则表达式)法…

LeetCode - Easy - 169. Majority Element

Topic ArrayDivide and ConquerBit Manipulation Description https://leetcode.com/problems/majority-element/ Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume t…

java 静态方法 异常_java空指针异常与静态方法

从一道经典面试题说起&#xff0c;public class HaHa {public static void haha(){System.out.println("haha");}public static void main(String[] args){((HaHa)null).haha();}}打印结果 haha。这段题考查两点知识&#xff0c;java的空指针异常和静态方法。1&#…

java中的asList_Java中的Arrays.asList()方法

Arrays.asList()返回一个List&#xff0c;但是这种情况下&#xff0c;其底层的实现是一个final数组&#xff0c;因此不能调整其尺寸如下代码片段&#xff1a;package chapter11.t1;import java.util.*;public class AddingGroups {public static void main(String[] args) {Lis…

java控制面板作用_Java

1. JAVA 的特性和优势(1) Java的核心优势 跨平台/可移植性(2) 其他特性 安全性&#xff1b;面对对象&#xff1b;简单性&#xff1b;高性能&#xff1b;分布式&#xff1b;多线程&#xff1b;健壮性&#xff1b;① 强大的生态系统(3) Java与C的关系 Java是C的简化版(C—)2. JAV…

java es 数据批量导入_ElasticSearch—Java批量导入导出

网上找了很多&#xff0c;我的es是2.3.5版本&#xff0c;网上的客户端最少都是5.x版本&#xff0c;所以没有能用的。自己整合了一下 2.3.5版本的。pom文件&#xff1a;org.elasticsearchelasticsearch2.3.5com.alibabafastjson1.1.35org.apache.commonscommons-io1.3.2org.apac…

java原始模型模式_java设计模式--原始模型模式

简介原始模型模式属于对象的创建模式。通过一个原型对象来指明要创建对象的类型&#xff0c;然后用复制原型对象的方法来创建出更多同类型的对象。Java所有的类都是从java.lang.Object类继承来的&#xff0c;Object类提供clone()方法对对象进行复制。一般调用clone()方法需要满…

Windows的命令行窗口运行Python时,如何清屏?

问题 如标题 解法 import os os.system("cls")参考 python实现清屏

手写文字识别java_java 手写文字图片识别提取 百度API

package org.fh.util;import org.json.JSONObject;import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.util.List;import java.util.Map;/*** 说明&#xff1a;获取文字识别token类* from&am…

LeetCode - Easy - 191. Number of 1 Bits

Topic Bit Manipulation Description https://leetcode.com/problems/number-of-1-bits/ Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight). Note: Note that in some languages such …

java并行计算同步返回_Java大文本并行计算实现过程解析

Java大文本并行计算实现过程解析简单提高文本读取效率&#xff0c;使用BufferedReader是个不错的选择。速度最快的方法是MappedByteBuffer&#xff0c;但是&#xff0c;相比BufferedReader而言&#xff0c;效果不是非常明显。也就是说&#xff0c;后者虽然快&#xff0c;但也快…

wgs utm java,Java,将经纬度转换为UTM

Does anyone know of a way, in Java, to convert an earth surface position from lat, lon to UTM (say in WGS84)? Im currently looking at Geotools but unfortunately the solution is not obvious.解决方案I was able to use Geotools 2.4 to get something that works…

java 指定时间转换_Java中使用Calendar进行获取指定时间,使用SimpleDateFormat进行格式化转换...

java中使用Calendar获取指定的时间public class DateTranslate {/*** 获取指定日期的间隔月份的第一天的日期* param date* param sep* return*/public static Date getMonthFirstDay(Date date, Integer sep) {Calendar cal Calendar.getInstance();cal.setTime(getThisWeekM…

java mvc 菜鸟_【java框架】SpringMVC(1)--SpringMVC入门

1.SpringMVC框架认识Spring MVC是一个基于MVC模式的Web框架&#xff0c;SpringMVC作为Spring中的一个模块&#xff0c;它与Spring能够无缝集成&#xff0c;主要用于解决企业Web开发中常见的问题&#xff1a;如参数接收、文件上传、表单验证、国际化等等。2.SpringMVC HelloWorl…

php设置cookie 域名,php如何设置cookie对整个域名有效?

php设置cookie对整个域名有效的方法&#xff1a;由setcookie函数让cookie对整个域名有效&#xff0c;代码为【setcookie("cookie_test", this is cookie test, time()3600,"/",“】。php设置cookie对整个域名有效的方法&#xff1a;默认情况下的cookie仅对…

php 配置 gd2,配置PHP对gd库的支持

搭建zabbix的时候遇到有对PHP的需求检测&#xff0c;发现没有对gd的支持&#xff0c;记录下。。。GD库是php处理图形的扩展库&#xff0c;它提供了一系列用来处理图片的API&#xff0c;使用GD库可以处理图片&#xff0c;或者生成图片&#xff0c;也可以给图片加水印。1、安装zl…

我的世界一个程序导致JAVA,Java地位无可动摇的12个原因

如今&#xff0c;面对曾经在程序员中被各种新技术掩盖直至堙灭的技术值得怀念。犹如COBOL这当年被老程序员们尊为神器的语言如今也基本没有价值。而Java作为现代程序员的中坚力量在这点上或许会成为下一个COBOL。有关JAVA的技术卖出多少本书已经是一个很久远的记忆了。现处中年…