官术网_书友最值得收藏!

Hamcrest

Hamcrest adds a lot of methods called matchers. Each matcher is designed to perform a comparison operation. It is extensible enough to support custom matchers created by yourself. Furthermore, JUnit supports Hamcrest natively since its core is included in the JUnit distribution. You can start using Hamcrest effortlessly. However, we want to use the full-featured project so we will add a test dependency to Gradle's file:

testCompile 'org.hamcrest:hamcrest-all:1.3' 

Let us compare one assert from JUnit with the equivalent one from Hamcrest:

  • The JUnit assert:
List<String> friendsOfJoe = 
Arrays.asList("Audrey", "Peter", "Michael", "Britney", "Paul");
Assert.assertTrue( friendships.getFriendsList("Joe")
.containsAll(friendsOfJoe));
  • The Hamcrest assert:
assertThat( 
  friendships.getFriendsList("Joe"), 
  containsInAnyOrder("Audrey", "Peter", "Michael", "Britney", "Paul") 
); 

As you can see, Hamcrest is a bit more expressive. It has a much bigger range of asserts that allows us to avoid some boilerplate code and, at the same time, makes code easier to read and is more expressive.

Here's another example:

  • JUnit assert:
Assert.assertEquals(5, friendships.getFriendsList("Joe").size()); 
  • Hamcrest assert:
assertThat(friendships.getFriendsList("Joe"), hasSize(5)); 

You'll notice two differences. The first is that, unlike JUnit, Hamcrest works almost always with direct objects. While in the case of JUnit, we needed to get the integer size and compare it with the expected number (5); Hamcrest has a bigger range of asserts so we can simply use one of them (hasSize) together with the actual object (List). Another difference is that Hamcrest has the inverse order with the actual value being the first argument (like TestNG).

Those two examples are not enough to show the full potential offered by Hamcrest. Later on in this book, there will be more examples and explanations of Hamcrest. Visit http://hamcrest.org/ and explore its syntax.

The complete source code can be found in the FriendshipsHamcrestTest class in the https://bitbucket.org/vfarcic/tdd-java-ch02-example-junit repositories.

主站蜘蛛池模板: 济南市| 会昌县| 凭祥市| 沽源县| 新竹市| 扎兰屯市| 伊金霍洛旗| 西盟| 会同县| 汉寿县| 惠来县| 蒙城县| 甘孜| 河东区| 堆龙德庆县| 沁阳市| 常州市| 岗巴县| 合肥市| 桂阳县| 黄骅市| 芦山县| 泰来县| 乌兰察布市| 湖南省| 外汇| 英山县| 香港 | 堆龙德庆县| 鹤山市| 浪卡子县| 洪洞县| 冷水江市| 定边县| 额尔古纳市| 烟台市| 枣庄市| 南靖县| 兰溪市| 高安市| 文登市|