Hamcrest Matchers


Hamcrest is a library of matchers, is an external add-on of the Junit Framework and Junit 4.12 comprises of depreciated Hamcrest matchers, not all of them.

How to add hamcrest methods into your project by IntelliJ as shown below.

For example, we are writing a JUnit test with hamcrest “Is” method. First, click “assertThat” and then press alt+Enter then click “Static Import Method…”

junit_9

Then, select which library you want. I chose org.hamcrest

junit_10

Then click “is” and press alt+enter and select “Static Import Method…”

junit_11

Then, select “Is.is(org.hamcrest.core) method and import related hamcrest method.

junit_12

You can import all Hamcrest methods in this way.

If you want to download all of the matchers into your project, you should add the source .jar files or you should add Hamcrest maven dependency.

Java sources and maven dependency descriptions can be found in this link http://search.maven.org/#search|ga|1|g%3Aorg.hamcrest and a sample maven dependency is shown below.

In this tutorial I will explain and show examples of core hamcrest methods. If you want to learn much more about hamcrest, you can find all detailed in formation in Hamcrest documentation link http://hamcrest.org/JavaHamcrest/javadoc/1.3/

Matchers are used with the org.junit.Assert.assertThat() method. You can find their descriptions and examples in below table.

MatcherDescription & Example
AllOfCalculates the logical conjunction of multiple matchers. Examined object must match ALL of the specified matcher.

Example
assertThat(“myString”, allOf(startsWith(“my”), containsString(“Str”)))

AnyOfCalculates the logical disjunction of multiple matchers. Examined object matches ANY of the specified matchers.

Example
assertThat(“myString”, allOf(startsWith(“your”), containsString(“Str”)))

DescribedAsAdds a description to a Matcher

Example
assertThat(“Sunday”, describedAs(“Sunday is not Saturday.”, is(not(“Saturday”))));

IsDecorates another Matcher, retaining its behavior. In other words it checks given objects equality. Is method allows tests to be more meaningful/expressive.

Example
assertThat(cheese, is(equalTo(smelly)))
instead of:
assertThat(cheese, equalTo(smelly))

IsAnythingA matcher that always returns true.

Example
assertThat(“Onur”, is(anything(“Bla Bla Bla”)));

IsEqualIt checks given objects equality.

Example
assertThat("str", equalTo("str "));
or
assertThat("str ", is(equalTo("str ")));

IsInstanceOf Tests whether the value is an instance of a class.

Example
assertThat(myInstanceTest, instanceOf(InstanceTest.class));

IsNot<T> Creates a matcher that wraps an existing matcher, but inverts the logic by which it will match.

Example
assertThat(“onur”, is(not(equalTo(“mike”))));
IsNull<T>Checks whether value is null

Example
assertThat(myStr, is(nullValue()));

 IsSame<T>Creates a matcher that matches only when the examined object is the same instance as the specified target object.

Example
assertThat(str1, IsSame.<String>sameInstance(str2));

In below code you can find usage of all matchers. I also tried to emphasize their descriptions with inline comments.

You can also check nice examples of hamcrest matchers in here: https://github.com/leveluplunch/levelup-java-examples/blob/master/src/test/java/com/levelup/java/hamcrest/CoreMatchers.java

Summary

  • You learned how to use and the meanings of hamcrest matchers.
  • You practiced with hamcrest matchers examples.

Keywords

JUnit, hamcrest matchers, unit testing, test framework

javafx

Database Operations in JavaFX

By Onur Baskirt / Apr 1, 2016 / 56 Comments
Before started this section, please check the first article and learn How to Start JAVAFX! http://www.swtestacademy.com/getting-started-with-javafx/ At first, part of JavaFX tutorial series, we created a sample JavaFX project, designed the draft version of the UI and set up an...
extentreports

How to Write Smart XPath Locators

By Onur Baskirt / Sep 24, 2017 / 5 Comments
Hi all, in this tutorial, I will describe you how to write smart and non-brittle XPath locators. When we write our test scripts, we generally prefer to use id, name, class, etc. these kinds of locators. However, sometimes we could not...
extentreports

How to Write Effective CSS Locators

By Onur Baskirt / Oct 1, 2017 / 0 Comments
Hi all, in this tutorial, I will describe you how to write effective CSS locators to interrogate web elements for your automation projects. As a rule of thumb, your interrogation strategy should be in below order: First try to use...
rest assured

REST API Testing with Rest Assured

By Onur Baskirt / Mar 8, 2016 / 32 Comments
Outline In this post, I will explain what is API and API testing, what is the difference between SOAP and REST services, and how to test REST APIs with Rest Assured Library. What is API? API stands for Application Programming...
javafx

Getting Started with JavaFX

By Onur Baskirt / Mar 25, 2016 / 0 Comments
When I started to work in my current position, one of my task is to do manual operations for campaign products  every week. After the second week, I thought that I have to automate this task using a GUI based...
extentreports

Selenium-1: Quick Start to Automation with Selenium WebDriver & JAVA & JUnit & Maven & IntelliJ

By Onur Baskirt / Sep 8, 2015 / 26 Comments
Outline Selenium Webdriver is the most popular open source web test automation framework across the wide range of browsers and platforms. In this tutorial, you will learn how to do web test automation with Selenium Webdriver and the related tools....
extentreports

Selenium-11: Execute JavaScript with JavascriptExecutor

By Onur Baskirt / Jan 27, 2016 / 15 Comments
Outline Sometimes we cannot handle some conditions or problems with Webdriver, web controls don't react well against selenium commands. In this kind of situations, we use Javascript. It is useful for custom synchronizations, hide or show the web elements, change...
page object model

Page Object Model with C#

By Ege Aksoz / Jun 18, 2017 / 8 Comments
In the previous tutorial, we’ve taken the initial steps and entered the world of automated testing. We also wrote our first automated test. From this point on, since we are not just going to write one test, we need to...
extentreports

How to Select a Date From DatePicker Using Selenium

By Onur Baskirt / Aug 13, 2016 / 6 Comments
When you need to automate a airway, hotel, or similar websites you need to deal with Datepickers and some times it is a little bit cumbersome to select a specific date on the Datepicker or calendar.  In this post, I...

Getting Started with RobotFramework on Windows

By Onur Baskirt / Apr 25, 2016 / 12 Comments
What is RobotFramework? RobotFramework is a GENERIC test automation framework for acceptance testing and acceptance test-driven development (ATTD). What it means that you can do web, mobile, desktop and other test automation activities with related test libraries. These libraries can...
By | 2017-10-22T03:10:38+00:00 November 22nd, 2015|JUnit, Test Frameworks, Unit Testing|0 Comments

About the Author:

Onur Baskirt
Onur Baskirt is a senior IT professional with 10+ years of experience. He worked at Bahçesehir University, ST Microelectronics, Huawei and Ericsson as research assistant, design verification engineer and software test leader. Also, he worked as software test leader and software operations manager at Turkey's biggest technology retailer, Teknosa. Now, he is working as Head of Software Testing and Manager of two Development Teams at Kariyer.net. His current research areas are technical software testing, programming, and computer science. Formerly, he has several research works and papers on digital chip design & verification. His hobbies are sport, dancing, traveling, and nutrition. You can find detailed information about him on his linked-in page.

Leave A Comment