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.pswp.cn/news/371186.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/371186.shtml
英文地址,請注明出處:http://en.pswp.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;原型定…