日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

JUnit和Hamcrest:在assertEquals上进行改进

發布時間:2023/12/3 编程问答 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JUnit和Hamcrest:在assertEquals上进行改进 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在我的博客文章中,Java越來越接受靜態導入嗎? ,我討論了在Java中越來越多地使用靜態導入來使代碼在某些情況下更流暢。 Java 單元測試特別受靜態導入的影響,在此博客文章中,我提供了一個簡單的示例,說明如何使用靜態導入來使用JUnit和Hamcrest進行更流暢的單元測試。

下一個代碼清單是一個簡單的IntegerArithmetic類,它具有一個需要進行單元測試的方法。

IntegerArithmetic.java

package dustin.examples;/*** Simple class supporting integer arithmetic.* * @author Dustin*/ public class IntegerArithmetic {/*** Provide the product of the provided integers.* * @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 multipleIntegers(final int ... integers){int returnInt = 1;for (final int integer : integers){returnInt *= integer;}return returnInt;} }

接下來顯示測試上述方法的一個方面的一種通用方法。

/*** Test of multipleIntegers method, of class IntegerArithmetic, using standard* JUnit assertEquals.*/@Testpublic void testMultipleIntegersWithDefaultJUnitAssertEquals(){final int[] integers = {2, 3, 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.multipleIntegers(integers);assertEquals(expectedResult, result);}

在上面顯示的相當典型的單元測試示例中,由于org.junit.Assert。*的靜態導入(未顯示),因此以流暢的方式調用了JUnit的assertEquals 。 但是,最新版本的JUnit( JUnit 4.4+ )已經開始包括Hamcrest核心匹配器,這可以進行更流暢的測試,如下面的代碼片段所示。

/*** Test of multipleIntegers method, of class IntegerArithmetic, using core* Hamcrest matchers included with JUnit 4.x.*/@Testpublic void testMultipleIntegersWithJUnitHamcrestIs(){final int[] integers = {2, 3, 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.multipleIntegers(integers);assertThat(result, is(expectedResult));}

在此示例中,JUnit的assertThat (自JUnit 4.4起也可作為org.junit.Assert.*的靜態導入的一部分)與隨附的Hamcrest核心匹配器is()結合使用。 這當然是一個問題,但是我更喜歡第二種方法,因為它對我來說更具可讀性。 斷言某些東西(結果)比其他方法(預期的)似乎更具可讀性和流利性。 記住使用assertEquals時先列出預期結果還是實際結果有時會很棘手,結合使用assertThat和is()可以減少我編寫和讀取測試時的工作。 歡迎減少工作量,尤其是乘以大量測試時。

參考:在Inspired by Actual Events博客上,我們的JCG合作伙伴 Dustin Marx 通過JUnit和Hamcrest改進了assertEquals 。


翻譯自: https://www.javacodegeeks.com/2012/05/junit-and-hamcrest-improving-on.html

總結

以上是生活随笔為你收集整理的JUnit和Hamcrest:在assertEquals上进行改进的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。