JUnit和Hamcrest:在assertEquals上进行改进
下一個代碼清單是一個簡單的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上进行改进的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 三脚金蟾怎样摆放(三足金蟾招财摆放)
- 下一篇: NetBeans 7.1:创建自定义提示