Improved assertions – Introduction

Matchers are the way to validate the result in your test script. Hamcrest is a Java library of Matchers objects. Hamcrest has been ported to several languages, like: Java, C++, Objective-C, Python, ActionScript 3, PHP, JavaScript and Erlang. The benefit of using Hamcrest is that it is very readable and it will produce fluent error messages when the assertion fails. It comes with matchers to verify text, numbers, collections, objects and even with logical matchers to combine matchers. It is also possible to create your own matchers which fit your domain language.

We can use static import to reduce the amount of code you have to write. Specifically, we can add the following lines to the import section:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

In this chapter you will find some examples on how to use the matchers and more importantly you must know beforehand and specify what the expected output is.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.