- Test-Driven Java Development(Second Edition)
- Alex Garcia Viktor Farcic
- 288字
- 2021-06-24 18:31:47
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.
- Learning Scala Programming
- Java系統分析與架構設計
- Unity Virtual Reality Projects
- 你必須知道的204個Visual C++開發問題
- 深入淺出Serverless:技術原理與應用實踐
- 大學計算機基礎實驗指導
- Julia高性能科學計算(第2版)
- jQuery Mobile移動應用開發實戰(第3版)
- C語言開發基礎教程(Dev-C++)(第2版)
- “笨辦法”學C語言
- 小程序,巧應用:微信小程序開發實戰(第2版)
- Learning Android Application Testing
- 大學計算機基礎實訓教程
- C語言程序設計與應用實驗指導書(第2版)
- 打造流暢的Android App