idea内置junit5_JUnit的内置Hamcrest Core Matcher支持

idea内置junit5

在通过JUnit和Hamcrest改善对assertEquals的文章中,我简要讨论了Hamcrest “ 核心 ”匹配器与JUnit的现代版本“结合”在一起的情况。 在那篇文章中,我特别关注了JUnit的assertThat(T,Matcher)静态方法与Hamcrest核心is()匹配器的结合使用,该方法自动包含在更高版本的JUnit中。 在本文中,我将介绍与最新版本的JUnit捆绑在一起的其他Hamcrest“核心”匹配器。

JUnit包括开箱即用的Hamcrest “核心”匹配器的两个优点是,无需专门下载Hamcrest,也无需在单元测试类路径中明确包含它。 在查看更多方便的Hamcrest“核心”匹配器之前,重要的是要在此指出,我有意重复提及“核心” Hamcrest匹配器,因为JUnit的最新版本仅提供“核心”( 并非全部 )Hamcrest匹配器自动。 仍然需要单独下载核心匹配器之外的任何Hamcrest匹配器,并在单元测试类路径上明确指定。 了解什么是Hamcrest“核心”(以及在最新版本的JUnit中默认情况下可用的匹配器)的一种方法是查看该程序包的基于Javadoc的API文档 :

从JUnit提供的org.hamcrest.core软件包的文档中,我们可以找到以下匹配器(及其描述):

Javadoc类说明 覆盖这里?
AllOf <T> 计算两个匹配器的逻辑合。
AnyOf <T> 计算两个匹配器的逻辑和。
DescribedAs <T> 为另一个匹配器提供自定义描述。
是<T> 装饰另一个Matcher,保留其行为,但允许测试更具表现力。 再次
IsAnything <T> 始终返回true的匹配器。 没有
IsEqual <T> 根据Object.equals(java.lang.Object)invokedMethod测试,该值是否等于另一个值?
IsInstanceOf 测试值是否为类的实例。
IsNot <T> 计算匹配器的逻辑取反。
IsNull <T> 值是否为空?
IsSame <T> 该值与另一个值是同一对象吗?

在我先前的演示Hamcrest is()匹配器与JUnit的assertThat()结合使用的文章中,我使用了IntegerArithmetic实现作为测试工具。 我将在这里再次使用它来演示其他一些Hamcrest核心匹配器。 为方便起见,该类复制如下。

IntegerArithmetic.java

package dustin.examples;/*** Simple class supporting integer arithmetic.* * @author Dustin*/
public class IntegerArithmetic
{/*** Provide the product of the provided integers.* * @param firstInteger First integer to be multiplied.* @param secondInteger Second integer to be multiplied.* @param integers Integers to be multiplied together for a product.* @return Product of the provided integers.* @throws ArithmeticException Thrown in my product is too small or too large*     to be properly represented by a Java integer.*/public int multiplyIntegers(final int firstInteger, final int secondInteger, final int ... integers){int returnInt = firstInteger * secondInteger;for (final int integer : integers){returnInt *= integer;}return returnInt;}
}

在“ 使用JUnit和Hamcrest改进assertEquals”中 ,我主要依靠is()来比较预期结果和实际结果,以测试整数乘法。 另一个选择是使用equalTo匹配器,如下面的代码清单所示。

使用Hamcrest equalTo()

/*** Test of multiplyIntegers method, of class IntegerArithmetic, using core* Hamcrest matcher equalTo.*/@Testpublic void testWithJUnitHamcrestEqualTo(){final int[] integers = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};final int expectedResult = 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 *13 * 14 * 15;final int result = this.instance.multiplyIntegers(2, 3, integers);assertThat(result, equalTo(expectedResult));}

尽管不是必需的,但有些开发人员喜欢将isequalTo一起使用,因为它们对他们来说更流利。 这就是is的存在的原因:更流畅地使用其他匹配器。 我经常equalTo()使用is() (暗示equalTo() ),如通过JUnit和Hamcrest改进对assertEquals所讨论的。 下一个示例演示了将is()匹配器与equalTo匹配器结合使用。

将Hamcrest equalTo()与is()结合使用

/*** Test of multiplyIntegers method, of class IntegerArithmetic, using core* Hamcrest matcher equalTo with "is" Matcher..*/@Testpublic void testWithJUnitHamcrestEqualToAndIsMatchers(){final int[] integers = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};final int expectedResult = 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 *13 * 14 * 15;final int result = this.instance.multiplyIntegers(2, 3, integers);assertThat(result, is(equalTo(expectedResult)));}

equalTo Hamcrest匹配器执行类似于调用Object.equals(Object)的比较。 实际上,其比较功能依赖于底层对象的equals(Object)实现的使用。 这意味着最后两个示例将通过,因为所比较的数字在逻辑上是等效的。 当想要确保更大的身份相等性时(实际上是相同的对象,而不仅仅是相同的逻辑内容),可以使用Hamcrest sameInstance匹配器,如下面的代码清单所示。 因为断言是正确的,所以也应用了not匹配器,因为只有预期的和实际的结果不是相同的实例,因此测试仅在“不”的情况下通过测试!

使用Hamcrest sameInstance()和not()

/*** Test of multiplyIntegers method, of class IntegerArithmetic, using core* Hamcrest matchers not and sameInstance.*/@Testpublic void testWithJUnitHamcrestNotSameInstance(){final int[] integers = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};final int expectedResult = 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 *13 * 14 * 15;final int result = this.instance.multiplyIntegers(2, 3, integers);assertThat(result, not(sameInstance(expectedResult)));}

有时需要控制从失败的单元测试的断言中输出的文本。 JUnit包括核心Hamcrest匹配器asDescribed()来支持此功能。 下一个清单中显示了这样的代码示例,代码清单后的NetBeans IDE的屏幕快照中显示了失败测试(和相应的断言)的输出。

将Hamcrest asDescribed()与sameInstance()一起使用

/*** Test of multiplyIntegers method, of class IntegerArithmetic, using core* Hamcrest matchers sameInstance and asDescribed. This one will assert a* failure so that the asDescribed can be demonstrated (don't do this with* your unit tests as home)!*/@Testpublic void testWithJUnitHamcrestSameInstanceDescribedAs(){final int[] integers = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};final int expectedResult = 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 *13 * 14 * 15;final int result = this.instance.multiplyIntegers(2, 3, integers);assertThat(result,describedAs("Not same object (different identity reference)",sameInstance(expectedResult)));}

当关联的单元测试断言失败时,使用describedAs()允许报告更有意义的消息。

现在,我将使用另一个人为设计的类来帮助说明最新版本的JUnit可用的其他核心Hamcrest匹配器。 接下来显示“需要测试”。

SetFactory.java

package dustin.examples;import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;/*** A Factory that provides an implementation of a Set interface based on* supplied SetType that indicates desired type of Set implementation.* * @author Dustin*/
public class SetFactory<T extends Object>
{public enum SetType{ENUM(EnumSet.class),HASH(HashSet.class),SORTED(SortedSet.class), // SortedSet is an interface, not implementationTREE(TreeSet.class),RANDOM(Set.class);       // Set is an interface, not a concrete collectionprivate Class setTypeImpl = null;SetType(final Class newSetType){this.setTypeImpl = newSetType;}public Class getSetImplType(){return this.setTypeImpl;}}private SetFactory() {}public static SetFactory newInstance(){return new SetFactory();}/*** Creates a Set using implementation corresponding to the provided Set Type* that has a generic parameterized type of that specified.* * @param setType Type of Set implementation to be used.* @param parameterizedType Generic parameterized type for the new set.* @return Newly constructed Set of provided implementation type and using*    the specified generic parameterized type; null if either of the provided*    parameters is null.* @throws ClassCastException Thrown if the provided SetType is SetType.ENUM,*    but the provided parameterizedType is not an Enum.*/public Set<T> createSet(final SetType setType, final Class<T> parameterizedType){if (setType == null || parameterizedType == null){return null;}Set<T> newSet = null;try{switch (setType){case ENUM:if (parameterizedType.isEnum()){newSet = EnumSet.noneOf((Class<Enum>)parameterizedType);}else{throw new ClassCastException("Provided SetType of ENUM being supplied with "+ "parameterized type that is not an enum ["+ parameterizedType.getName() + "].");}break;case RANDOM:newSet = LinkedHashSet.class.newInstance();break;case SORTED:newSet = TreeSet.class.newInstance();break;default:newSet = (Set<T>) setType.getSetImplType().getConstructor().newInstance();break;}}catch (  InstantiationException| IllegalAccessException| IllegalArgumentException| InvocationTargetException| NoSuchMethodException ex){Logger.getLogger(SetFactory.class.getName()).log(Level.SEVERE, null, ex);}return newSet;}
}

刚刚显示了代码的人为的类提供了使用其他Hamcrest“核心”匹配器的机会。 如上所述,可以将所有这些匹配与is匹配器一起使用,以提高语句的流畅性。 两个有用的“核心”的匹配是nullValue()notNullValue()这两者在未来基于JUnit的代码列表被证实(和is结合使用在一种情况下)。

使用Hamcrest nullValue()和notNullValue()

/*** Test of createSet method, of class SetFactory, with null SetType passed.*/@Testpublic void testCreateSetNullSetType(){final SetFactory factory = SetFactory.newInstance();final Set<String> strings = factory.createSet(null, String.class);assertThat(strings, nullValue());}/*** Test of createSet method, of class SetFactory, with null parameterized type* passed.*/@Testpublic void testCreateSetNullParameterizedType(){final SetFactory factory = SetFactory.newInstance();final Set<String> strings = factory.createSet(SetType.TREE, null);assertThat(strings, is(nullValue()));}@Testpublic void testCreateTreeSetOfStringsNotNullIfValidParams(){final SetFactory factory = SetFactory.newInstance();final Set<String> strings = factory.createSet(SetType.TREE, String.class);assertThat(strings, notNullValue());}

Hamcrest匹配器instanceOf也很有用,并在下一个代码清单中进行演示(一个单独使用instanceOf的示例和一个与is一起使用的示例)。

使用Hamcrest instanceOf()

@Testpublic void testCreateTreeSetOfStringsIsTreeSet(){final SetFactory factory = SetFactory.newInstance();final Set<String> strings = factory.createSet(SetType.TREE, String.class);assertThat(strings, is(instanceOf(TreeSet.class)));}@Testpublic void testCreateEnumSet(){final SetFactory factory = SetFactory.newInstance();final Set<RoundingMode> roundingModes = factory.createSet(SetType.ENUM, RoundingMode.class);roundingModes.add(RoundingMode.UP);assertThat(roundingModes, instanceOf(EnumSet.class));}

到目前为止,许多Hamcrest核心匹配器都提供了更高的流畅性和可读性,但出于更多原因,我喜欢接下来的两个匹配器。 Hamcrest hasItem()匹配器检查集合中指定项的存在,更有用的Hamcrest hasItems()匹配器检查集合中多个规定项的存在。 在代码中更容易看到这一点,下面的代码演示了它们的实际作用。

使用Hamcrest hasItem()和hasItems()

@Testpublic void testCreateTreeSetOfStringsHasOneOfAddedStrings(){final SetFactory factory = SetFactory.newInstance();final Set<String> strings = factory.createSet(SetType.TREE, String.class);strings.add("Tucson");strings.add("Arizona");assertThat(strings, hasItem("Tucson"));}@Testpublic void testCreateTreeSetOfStringsHasAllOfAddedStrings(){final SetFactory factory = SetFactory.newInstance();final Set<String> strings = factory.createSet(SetType.TREE, String.class);strings.add("Tucson");strings.add("Arizona");assertThat(strings, hasItems("Tucson", "Arizona"));}

有时需要测试某种测试方法的结果,以确保它满足各种各样的期望。 这就是Hamcrest allOf匹配器派上用场的地方。 此匹配器确保所有条件(表示为匹配器)都为真。 在下面的代码清单中对此进行了说明,该清单测试了一个断言,即所生成的Set不为null,具有两个特定的String且是TreeSet的实例。

使用Hamcrest allOf()

@Testpublic void testCreateSetAllKindsOfGoodness(){final SetFactory factory = SetFactory.newInstance();final Set<String> strings = factory.createSet(SetType.TREE, String.class);strings.add("Tucson");strings.add("Arizona");assertThat(strings,allOf(notNullValue(), hasItems("Tucson", "Arizona"), instanceOf(TreeSet.class)));}

为了演示Hamcrest核心“ anyOf”匹配器提供了现成的JUnit更新版本,我将使用另一个需要单元测试的可笑的Java类。

今天.java

package dustin.examples;import java.util.Calendar;
import java.util.Locale;/*** Provide what day of the week today is.* * @author Dustin*/
public class Today
{/*** Provide the day of the week of today's date.* * @return Integer representing today's day of the week, corresponding to*    static fields defined in Calendar class.*/public int getTodayDayOfWeek(){return Calendar.getInstance(Locale.US).get(Calendar.DAY_OF_WEEK);}
}

现在,我需要测试上述类中的唯一方法是否正确返回了代表星期几的有效整数。 我希望我的测试确保返回代表星期天到星期六的一天的有效整数,但是要测试的方法是这样的,使得它可能与任何给定的测试运行都不是一周中的同一天。 下面的代码清单指示如何使用包含JUnit的Hamcrest“ anyOf”匹配器进行测试。

使用Hamcrest anyOf()

/*** Test of getTodayDayOfWeek method, of class Today.*/@Testpublic void testGetTodayDayOfWeek(){final Today instance = new Today();final int todayDayOfWeek = instance.getTodayDayOfWeek();assertThat(todayDayOfWeek,describedAs("Day of week not in range.",anyOf(is(Calendar.SUNDAY),is(Calendar.MONDAY),is(Calendar.TUESDAY),is(Calendar.WEDNESDAY),is(Calendar.THURSDAY),is(Calendar.FRIDAY),is(Calendar.SATURDAY))));}

尽管Hamcrest的allOf要求所有条件都必须匹配才能避免断言,但任何一个条件的存在足以确保anyOf不会导致失败的断言。

我最喜欢的确定JUnit可用的核心Hamcrest匹配器的方法是在Java IDE中使用导入完成。 当我静态导入org.hamcrest.CoreMatchers.*软件包内容时,将显示所有可用的匹配器。 我可以在IDE中查看*代表什么,以查看对我可用的匹配器。

JUnit包含Hamcrest“核心”匹配器真是太好了,这篇文章试图演示其中的大多数。 Hamcrest在“核心”之外还提供了许多有用的匹配器,它们也很有用。 有关详细信息,请参见Hamcrest教程 。

参考:在Inspired by Actual Events博客上,我们的JCG合作伙伴 Dustin Marx提供了JUnit的内置Hamcrest Core Matcher支持 。


翻译自: https://www.javacodegeeks.com/2012/06/junits-built-in-hamcrest-core-matcher.html

idea内置junit5

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

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

相关文章

jenkins 发送邮件模板

jenkins 发送邮件模板 <!DOCTYPE html> <html> <head> <meta charset"UTF-8"> <title>${ENV, var"JOB_NAME"}-第${BUILD_NUMBER}次构建日志</title> </head><body leftmargin"8" marginwidth"…

centos lnmp源码安装mysql_CentOS 6.6 下源码编译安装MySQL 5.7.5

说明&#xff1a;CentOS 6.6 下源码编译安装MySQL 5.7.51. 安装相关工具# yum -y install gcc-c ncurses-devel cmake make perl \gcc autoconf automake zlib libxml libgcrypt libtool bison2. 清理环境检查boost版本&#xff1a;# rpm -qa boost*卸载boost-*等库&#xff1a…

Oracle Spring Clean JavaFX应该吗?

我们确实在Codename One上依赖JavaFX&#xff0c;我们的模拟器需要它。 我们的桌面版本使用它&#xff0c;而我们的设计器工具基于Swing。 我们希望它成功&#xff0c;这对我们的业务至关重要&#xff01; 即使您是Java EE开发人员并且不关心桌面编程&#xff0c;我们也不是一个…

laravel mysql 锁表_Laravel中MySQL的乐观锁与悲观锁

MySQL/InnoDB的加锁&#xff0c;是一个老生常谈的话题。在数据库高并发请求下&#xff0c;如何兼顾数据完整性与用户体验的敏捷性是一代又一代程序员一直在思考的问题。乐观锁乐观锁之所以叫乐观&#xff0c;是因为这个模式不会对数据加锁。而是对数据操作保持一种乐观的心态&a…

python初心记录二

切片 L [1,2,3,4,5,6,7,8,9,0] L[0:3] L[-3] 迭代 如果给定一个list或tuple&#xff0c;我们可以通过for循环来遍历这个list或tuple&#xff0c;这种遍历我们称为迭代&#xff08;Iteration&#xff09;。 因为dict的存储不是按照list的方式顺序排列&#xff0c;所以&#xff0…

Spring对事物的实现

Spring对待事物的实现有一个标签可以使用Transactional标签来实现事务的管理&#xff0c;但是在使用的时候很多人不清楚实现的原理而使用了错误的使用方式&#xff0c;导致日志里的确是打印了&#xff0c;但是方法的确没有回滚。 我在遇到问题的时候发生了这样的问题&#xff0…

mysql 超长记录_谁记录了mysql error log中的超长信息(记pt-stalk一个bug的定位过程)...

【问题】最近查看MySQL的error log文件时&#xff0c;发现有很多服务器的文件中有大量的如下日志&#xff0c;内容很长(大小在200K左右)&#xff0c;从记录的内容看&#xff0c;并没有明显的异常信息。有一台测试服务器也有类似的问题&#xff0c;为什么会记录这些信息&#xf…

glassfish发布应用_Arquillian 1.0.0.Final正式发布! 准备使用GlassFish和WebLogic! 所有虫子死亡!...

glassfish发布应用红帽公司和JBoss社区今天宣布的1.0.0.Final发布的Arquillian &#xff0c;其屡获殊荣的建在Java虚拟机&#xff08;JVM&#xff09;运行测试平台。 Arquillian大大减少了编写和执行Java中间件集成和功能测试所需的工作。 它甚至使测试工程师能够解决以前认为无…

php中 ob_start()有什么作用

<?php ob_start(); //开启缓冲区 echo "这是第一次输出内容!\n"; $ff[1] ob_get_contents() ; //获取当前缓冲区内容 ob_flush();//缓冲器清除 echo "这是第二次输出内容!\n"; $ff[2] ob_get_contents() ; //获取当前缓冲区内容 echo "这是第三…

mysql mycat one_Mycat 整合 MySQL 8.x 踩坑实践

Mycat 目前还未全面支持MySQL 8以上的版本&#xff0c;可能会导致一些问题&#xff0c;例如Mycat连接MySQL 8时可能会报密码错误&#xff0c;因为新版的密码加密方式与旧版不一样。还有就是时区问题&#xff0c;新版的连接方式需要增加时区参数。除此之外&#xff0c;可能还会有…

使用ADF列表视图的主从数据

最近&#xff0c;从UI角度来看&#xff0c;ADF Faces 表组件不再被认为很酷。 对于显示数据集合&#xff0c; 列表视图今天应该很酷。 这并不意味着我们根本不应该使用af&#xff1a;table 。 在某些情况下&#xff08;经常是:)&#xff09;&#xff0c;表比列表视图更适合。 但…

mysql memory=off_MySQL内存调优

原文链接: MySQL Memory Allocation -- by Rick James原文日期: Created 2010; Refreshed Oct, 2012, Jan, 2014翻译人员: 铁锚翻译日期: 2014年5月28日MySQL 内存分配—— 高速设置方案假设仅使用MyISAM存储引擎,设置 key_buffer_size为可用内存的20%,(再加上设置 innodb_buff…

Seajs的用法

以前经常听到Seajs&#xff0c;但是没深入了解过&#xff0c;不清楚到底是用做哪个方面&#xff0c;后来调组到M站做开发&#xff0c;发现项目用到了Seajs&#xff0c;便去了解下 SeaJS是一个遵循CMD规范的JavaScript模块加载框架&#xff0c;可以实现JavaScript的模块化开发及…

java 调用私有方法_公开调用私有Java方法?

java 调用私有方法我们是Java开发人员&#xff0c;在Java中已知4种访问修饰符&#xff1a;私有&#xff0c;受保护&#xff0c;公共和包。 好吧&#xff0c;除了私有以外&#xff0c;最后三个可以通过继承&#xff0c;相同的包或实例从类外部调用。 现在&#xff0c;常见的问题…

mysql慢查询开启语句分析_linux下开启mysql慢查询,分析查询语句

mysql> show variables like "%long%"; //查看一下默认为慢查询的时间10秒----------------------------| Variable_name | Value |----------------------------| long_query_time | 10.000000 |----------------------------1 row in set (0.00 sec)mysql> s…

港航环境变化引起的错误解决方法

1.serlvet API缺少&#xff0c;pom.xml中引入坐标&#xff1b; 2.web.xml中出现错误&#xff0c;将所有的filter调到filtermapping上面去&#xff1b; 3.依赖导入完成后项目依然有红叉&#xff0c;右击项目Propreties->myeclipse->Project Facets->java换成1.6就可以了…

flutter 国际化_从0开始设计Flutter独立APP | 第二篇: 完整的国际化语言支持

鉴于Flutter高性能渲染和跨平台的优势&#xff0c;闪点清单在移动端APP上&#xff0c;使用了完整的Flutter框架来开发。既然是完整APP&#xff0c;架构搭建完全不受历史Native APP的影响&#xff0c;没有历史包袱的沉淀&#xff0c;设计也能更灵活和健壮。国际化语言的支持&…

将旧版本从Java EE 5减少到7

Java EE 5于2005年首次引入&#xff0c;而Java EE 7于2013年问世。这两个版本之间有7年的差距&#xff0c;从技术角度来说&#xff0c;这就像一个世纪。 许多组织仍然对使用Java EE 5感到困惑&#xff0c;并且有很多正当理由选择不升级。 不过&#xff0c;如果您考虑一些前进的…

struts2知识

一、 MVC Model 1&#xff1a;将所有的程序代码&#xff0c;都写到JSP页面中。 Model 2&#xff1a;JSP&#xff08;流程控制、数据显示&#xff09; JavaBean 改进的Model2&#xff1a;Servlet&#xff08;流程控制&#xff09; Jsp&#xff08;数据显示&#xff09; Ja…

mysql 数据修改时间_怎样修改mysql数据中的具体时间

匿名用户1级2016-12-30 回答应用场景&#xff1a;1、在数据表中&#xff0c;要记录每条数据是什么时候创建的&#xff0c;不需要应用程序去特意记录&#xff0c;而由数据数据库获取当前时间自动记录创建时间&#xff1b;2、在数据库中&#xff0c;要记录每条数据是什么时候修改…