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

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.

主站蜘蛛池模板: 高唐县| 灌云县| 新民市| 伊金霍洛旗| 疏勒县| 历史| 达日县| 崇左市| 甘南县| 皮山县| 且末县| 无为县| 博客| 弥勒县| 鸡西市| 博爱县| 密山市| 资源县| 越西县| 德昌县| 靖远县| 依安县| 湖南省| 西城区| 鸡泽县| 渑池县| 建始县| 大厂| 平阳县| 永州市| 米林县| 崇礼县| 商南县| 临泉县| 大足县| 江北区| 宜都市| 隆安县| 天峻县| 若尔盖县| 中山市|