junit:junit_JUnit和Hamcrest:在assertEquals上进行改进
junit:junit
在我的博客文章中,Java越來(lái)越接受靜態(tài)導(dǎo)入嗎? 在本文中,我討論了在Java中越來(lái)越多地使用靜態(tài)導(dǎo)入來(lái)使代碼在某些情況下更加流暢。 Java中的 單元測(cè)試特別受靜態(tài)導(dǎo)入的影響,在此博客文章中,我提供了一個(gè)簡(jiǎn)單的示例,說(shuō)明如何使用靜態(tài)導(dǎo)入來(lái)使用JUnit和Hamcrest進(jìn)行更流暢的單元測(cè)試。下一個(gè)代碼清單是一個(gè)簡(jiǎn)單的IntegerArithmetic類(lèi),它具有一個(gè)需要進(jìn)行單元測(cè)試的方法。
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;} }接下來(lái)顯示測(cè)試上述方法的一個(gè)方面的一種通用方法。
/*** 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);}在上面顯示的相當(dāng)?shù)湫偷膯卧獪y(cè)試示例中,由于org.junit.Assert。*的靜態(tài)導(dǎo)入(未顯示),因此能夠流暢地調(diào)用JUnit的assertEquals 。 但是,最新版本的JUnit( JUnit 4.4+ )已經(jīng)開(kāi)始包括Hamcrest核心匹配器,這可以進(jìn)行更流暢的測(cè)試,如下一個(gè)代碼片段所示。
/*** 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.*的靜態(tài)導(dǎo)入的一部分)與隨附的Hamcrest核心匹配器is()結(jié)合使用。 這當(dāng)然是一個(gè)問(wèn)題,但是我更喜歡第二種方法,因?yàn)樗鼘?duì)我來(lái)說(shuō)更具可讀性。 斷言某些東西(結(jié)果)比其他方法(預(yù)期的)似乎更易讀,更流利。 記住使用assertEquals時(shí)先列出預(yù)期結(jié)果還是實(shí)際結(jié)果有時(shí)會(huì)很棘手,結(jié)合使用assertThat和is()可以減少我編寫(xiě)和讀取測(cè)試時(shí)的工作。 歡迎減少工作量,尤其是乘以大量測(cè)試時(shí)。
參考:在Inspired by Actual Events博客上,我們的JCG合作伙伴 Dustin Marx 與JUnit和Hamcrest一起改進(jìn)assertEquals 。
翻譯自: https://www.javacodegeeks.com/2012/05/junit-and-hamcrest-improving-on.html
junit:junit
總結(jié)
以上是生活随笔為你收集整理的junit:junit_JUnit和Hamcrest:在assertEquals上进行改进的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 美的电热水器怎么设置温度(美的电热水器怎
- 下一篇: win7系统下怎么关闭UAC功能?(wi