- 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.
- AngularJS Testing Cookbook
- Docker技術入門與實戰(第3版)
- 零基礎玩轉區塊鏈
- Java高手真經(高級編程卷):Java Web高級開發技術
- 認識編程:以Python語言講透編程的本質
- GitLab Repository Management
- Java:Data Science Made Easy
- Learning Neo4j 3.x(Second Edition)
- Learning Apache Kafka(Second Edition)
- Easy Web Development with WaveMaker
- NoSQL數據庫原理
- Python計算機視覺和自然語言處理
- 深入實踐C++模板編程
- Magento 2 Development Essentials
- ATmega16單片機C語言程序設計經典實例