junit:junit_JUnit和Hamcrest:在assertEquals上进行改进
junit:junit
在我的博客文章中,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:junit
總結
以上是生活随笔為你收集整理的junit:junit_JUnit和Hamcrest:在assertEquals上进行改进的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 美的电热水器怎么设置温度(美的电热水器怎
- 下一篇: win7系统下怎么关闭UAC功能?(wi