太原网站制作优化seo公司,济南中京网站建设公司,建设网站的步骤知乎,查询商标注册的官方网在我的博客文章中#xff0c;Java越来越接受静态导入吗#xff1f; #xff0c;我讨论了在Java中越来越多地使用静态导入来使代码在某些情况下更流畅。 Java 单元测试特别受静态导入的影响#xff0c;在此博客文章中#xff0c;我提供了一个简单的示例#xff0c;说明如何… 在我的博客文章中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