JUnit通过失败测试案例

为什么要建立一种预期测试失败的机制?

有一段时间,人们会希望并期望JUnit @Test案例失败。 尽管这种情况很少见,但确实发生了。 我需要检测JUnit测试何时失败,然后(如果期望的话)通过而不是失败。 具体情况是我正在测试一段代码,该代码可能会在对象调用内引发Assert错误。 该代码被编写为对流行的新Fest Assertions框架的增强,因此,为了测试功能,人们可能希望测试用例会故意失败。

一个解法

一种可能的解决方案是将JUnit @Rule提供的功能与注释形式的自定义标记一起使用。

为什么要使用@Rule?

@Rule对象为测试类和每个测试用例提供了类似于AOP的接口。 在运行每个测试用例之前,将重置规则,并且它们以@Around AspectJ建议的样式公开测试用例的工作方式。

必需的代码元素

  • @Rule对象检查每个@Test用例的状态
  • @ExpectedFailure自定义标记注释
  • 测试用例证明代码有效!
  • 如果带注释的测试用例没有失败,则抛出可选的特定异常

注意:工作代码在我的github页面上可用,并已添加到Maven Central。 随意分叉项目并提交拉取请求 Maven用法

<dependency><groupId>com.clickconcepts.junit</groupId><artifactId>expected-failure</artifactId><version>0.0.9</version>
</dependency>

用法示例

在此示例中,“ exception”对象是Fest断言增强的ExpectedException(请查看我的下一篇文章以展示此功能)。 预期的异常将产生断言,并且为了测试这些断言,必须将测试用例标记为@ExpectedFailure

public class ExceptionAssertTest {@Rulepublic ExpectedException exception = ExpectedException.none();@Rulepublic ExpectedTestFailureWatcher watcher = ExpectedTestFailureWatcher.instance();@Test@ExpectedFailure('The matcher should fail becasue exception is not a SimpleException')public void assertSimpleExceptionAssert_exceptionIsOfType() {// expected exception will be of type 'SimpleException'exception.instanceOf(SimpleException.class);// throw something other than SimpleException...expect failurethrow new RuntimeException('this is an exception');}
}

解决方案的实施

提醒一下,最新代码可在我的github页面上找到 。

@规则代码(ExpectedTestFailureWatcher.java)

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
// YEAH Guava!!
import static com.google.common.base.Strings.isNullOrEmpty;public class ExpectedTestFailureWatcher implements TestRule {/*** Static factory to an instance of this watcher** @return New instance of this watcher*/public static ExpectedTestFailureWatcher instance() {return new ExpectedTestFailureWatcher();}@Overridepublic Statement apply(final Statement base, final Description description) {return new Statement() {@Overridepublic void evaluate() throws Throwable {boolean expectedToFail = description.getAnnotation(ExpectedFailure.class) != null;boolean failed = false;try {// allow test case to executebase.evaluate();} catch (Throwable exception) {failed = true;if (!expectedToFail) {throw exception; // did not expect to fail and failed...fail}}// placed outside of catchif (expectedToFail && !failed) {throw new ExpectedTestFailureException(getUnFulfilledFailedMessage(description));}}/*** Extracts detailed message about why test failed* @param description* @return*/private String getUnFulfilledFailedMessage(Description description) {String reason = null;if (description.getAnnotation(ExpectedFailure.class) != null) {reason = description.getAnnotation(ExpectedFailure.class).reason();}if (isNullOrEmpty(reason)) {reason = 'Should have failed but didn't';}return reason;}};}
}


@ExpectedFailure定制注释(ExpectedFailure.java)

import java.lang.annotation.*;/*** Initially this is just a marker annotation to be used by a JUnit4 Test case in conjunction* with ExpectedTestFailure @Rule to indicate that a test is supposed to be failing*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.METHOD)
public @interface ExpectedFailure {// TODO: enhance by adding specific information about what type of failure expected//ClassassertType() default Throwable.class;/*** Text based reason for marking test as ExpectedFailure* @return String*/String reason() default '';
}

自定义异常(可选,您可以轻松地抛出RuntimeException或现有的自定义异常)

public class ExpectedTestFailureException extends Throwable {public ExpectedTestFailureException(String message) {super(message);}
}

一个人不能利用预期的故障标记能力吗?

强大的功能伴随着巨大的责任 ,建议您如果不完全了解测试失败的原因,请不要将测试标记为@ExpectedFailure。 建议谨慎执行此测试方法。 请勿使用@ExpectedFailure注释替代@Ignore

将来可能的增强可能包括指定在测试用例执行期间确定的特定断言或特定消息的方法。

已知的问题

在此当前状态下,@ ExpectedFailure批注可以掩盖其他声明,并且在将来进行增强之前,建议明智地使用此方法。

参考:在Mike的站点博客上,允许JUnit测试通过我们的JCG合作伙伴 Mike的失败测试案例 。


翻译自: https://www.javacodegeeks.com/2012/09/junit-pass-test-case-on-failures.html

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

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

相关文章

CentOS6.5安装MySQL5.7详细教程

CentOS6.5安装MySQL5.7详细教程 注&#xff1a;文中所写的安装过程均在CentOS6.5 x86下通过测试 主要参考博文&#xff1a; https://segmentfault.com/a/1190000003049498 http://www.th7.cn/db/mysql/201601/175073.shtml 1.检测系统是否已经安装过mysql或其依赖&#xff0c;若…

cmake 查看编译命令,以及在vscode中如何使用cmke

通过设置如下配置选项&#xff0c;可以生成compile_commands.json 文件&#xff0c;记录使用的编译命令 set(CMAKE_EXPORT_COMPILE_COMMANDS ON)获得现有模块列表 cmake --help-module-list查看命令文档 cmake --help-command find_file查看模块的详细信息 cmake --help-mo…

php学习八:封装

一&#xff1a;在php中&#xff0c;用class关键字来创建一个类&#xff0c;即进行封装&#xff1b;在类里面有成员属性和方法行为组成&#xff1a; 1.成员属性:用关键字var来声明,可以给初始值也可以不给;现在var废弃&#xff0c;用public来声明&#xff0c;public为共有属性&a…

纯Java JavaFX 2.0菜单

在有关JavaFX的最新文章中 &#xff0c;我集中讨论了不使用JavaFX 1.x的JavaFXScript和不使用JavaFX 2.0的新FXML来使用JavaFX 2.0的新Java API 。 所有这些示例均已使用标准Java编译器进行了编译&#xff0c;并使用标准Java启动 器执行。 在本文中&#xff0c;我将继续演示使用…

设置QtreeWidget水平滚动条

转载请注明出处&#xff1a;http://www.cnblogs.com/dachen408/p/7552603.html //设置treewidget水平滚动条 ui.treeWidget->header()->setSectionResizeMode(QHeaderView::ResizeToContents);ui.treeWidget->header()->setStretchLastSection(false);转载于:https…

java 序列化 uid,Java中的序列化版本uid

How is Serialization id stored in the instance of the object ?The Serialization id we declare in Java is static field;and static fields are not serialized.There should be some way to store the static final field then. How does java do it ?解决方案The ser…

HTML5本地存储

什么是Web Storage Web Storage是HTML5里面引入的一个类似于cookie的本地存储功能&#xff0c;可以用于客户端的本地存储&#xff0c;其相对于cookie来说有以下几点优势&#xff1a; 存储空间大&#xff1a;cookie只有4KB的存储空间&#xff0c;而Web Storage在官方建议中为每个…

番石榴秒表

番石榴的秒表是番石榴第10版的另一个新番石榴类&#xff08;作为Optional &#xff0c;这是另一篇近期文章的主题&#xff09;。 顾名思义&#xff0c;这个简单的类提供了一种方便地测量两个代码点之间经过的时间的方法。 与使用System.currentTimeMillis&#xff08;&#xff…

CF 839 E-最大团

CF 839 E Soltion: 就是怎么求最大团的问题: 以下是\(O(7000\times n^2)\)的做法 求一个最大团,然后将所有的药水平均分配,到最大团的所有点上,计算答案. #include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorit…

sse java_SSE详解

SSE(Server-Sent Events):通俗解释起来就是一种基于HTTP的&#xff0c;以流的形式由服务端持续向客户端发送数据的技术应用场景由于HTTP是无状态的传输协议,每次请求需由客户端向服务端建立连接,HTTPS还需要交换秘钥&#xff0c;所以一次请求,建立连接的过程占了很大比例在http…

520. Detect Capital

题目&#xff1a; Given a word, you need to judge whether the usage of capitals in it is right or not. We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA".A…

盒模型的属性丶display显示丶浮动

一丶盒模型的属性(重要) 1.padding padding是标准文档流,父子之间调整位置 <!DOCTYPE html><html><head><meta charset"UTF-8"><title>padding</title><style>*{padding: 0;margin: 0;}.box{width: 200px;height: 200px;b…

MapReduce:通过数据密集型文本处理

自上次发布以来已经有一段时间了&#xff0c;因为我一直在忙于Coursera提供的一些课程。 有一些非常有趣的产品&#xff0c;值得一看。 前一段时间&#xff0c;我购买了Jimmy Lin和Chris Dyer的MapReduce数据密集型处理程序 。 本书以伪代码格式介绍了几种关键的MapReduce算法。…

ubuntu(deepin)安装apache2并支持php7.0

linux虚拟机下用于开发环境测试&#xff0c;安装的apache和php7.0&#xff0c;但是简单安装完两者后apache并不能解析php&#xff0c;原因是确实apache的php扩展。 # 首先安装apache sudo apt-get install apache2 # 然后安装php7.0 sudo apt-get install php7.0 # 一般执行完这…

java applet 换行_Java复习题

一、选择题1.有Java语句如下&#xff0c;则说法正确的是()A.此语句是错误的B. a.length的值为5C. b.length的值为5D. a.length和b.length的值都为52.整数除法中&#xff0c;如果除数为0&#xff0c;则将导致的异常是( B )A. NullPointerExceptionB. ArithmeticExceptionC. Arra…

解决:MVC对象转json包含\r \n

项目中对象转json字符串时&#xff0c;如下&#xff1a;JsonSerializerSettings jsetting new JsonSerializerSettings(); jsetting.DefaultValueHandling DefaultValueHandling.Ignore; return JsonConvert.SerializeObject(resultMoldels, Formatting.Indented, jsetting);…

CSS 小结笔记之滑动门技术

所谓的滑动门技术&#xff0c;就是指盒子背景能够自动拉伸以适应不同长度的文本。即当文字增多时&#xff0c;背景看起来也会变长。 大多数应用于导航栏之中&#xff0c;如微信导航栏: 具体实现方法如下&#xff1a; 1、首先每一块文本内容是由a标签与span标签组成 <a hr…

使用API​​身份验证的Spring Security

背景 尽管有许多博客文章详细介绍了如何使用Spring Security&#xff0c;但是当问题域位于标准LDAP或数据库身份验证之外时&#xff0c;我仍然经常发现配置挑战。 在本文中&#xff0c;我将介绍一些针对Spring Security的简单自定义&#xff0c;使其能够与基于REST的API调用一起…

java nlpir_4-NLPIR汉语分词系统-JAVA

好吧&#xff0c;之前用的是旧版的&#xff0c;现在出了个新版的&#xff0c;优先选择用新版的哈。从官网下载相应的开发包&#xff0c;然后主要需要找到这几个东西添加到项目工程里面&#xff0c;1.Data文件夹 2.NLPIR_JNI.DLL 3.NLPIR.jar 4.nlpir.properties添加完那些东西后…

浅析C语言中assert的用法(转)

原文地址&#xff1a;http://www.jb51.net/article/39685.htm 以下是对C语言中assert的使用方法进行了介绍&#xff0c;需要的朋友可以参考下。 assert宏的原型定义在<assert.h>中&#xff0c;其作用是如果它的条件返回错误&#xff0c;则终止程序执行&#xff0c;原型定…