欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

JUnit和Hamcrest:在assertEquals上进行改进

发布时间:2023/12/3 61 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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上进行改进的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。