Hamcrest – Improve your tests with useful matchers

Introduction

For this hamcrest tutorial, i want to show multiple matches, which are very powerful. Therefore you can fully express your assertions. It provides a fluent and expressive way to define custom matchers for complex conditions and enhances the readability and maintainability of test code. Like always you can see all examples in my example repository.

Matchers

1. Basic Matchers

There are several types of matchers, like Object-matchers, Collection-matchers, Text-matchers and even Custom-matchers. Let’s just start with some very simple basic-matchers

Java
        String expected = "Hello";
        String actual = "Hello";

        assertThat(actual, equalTo(expected));

Like example show, we just check if actual and expected are equal.

Other examples of some Basic matchers are as following:

Matcher for TypeOperation
StringstartsWith, endsWith, containsString
NumbergreaterThan, lessThan, closeTo
ListhasSize, contains, hasItem
List
Java

int x = 10;
double y = 3.14;

// Number
assertThat(x, greaterThan(5));
assertThat(x, lessThan(20));
assertThat(y, closeTo(3.1, 0.1));

String sentence = "The quick brown fox jumps over the lazy dog";

// String
assertThat(sentence, startsWith("The"));
assertThat(sentence, endsWith("dog"));
assertThat(sentence, containsString("fox"));

List<String> fruits = Arrays.asList("apple", "banana", "orange");
// List
assertThat(fruits, hasSize(3));
assertThat(fruits, contains("apple", "banana", "orange"));
assertThat(fruits, hasItem("banana"));

2. Object Matchers

Let’s say we have a PersonObject

Java

@Getter
@Setter
@AllArgsConstructor
public class Person {

    private String name;
}
    @Test
    void objectMatcher() {
        Person johnDoe = new Person("John Doe");
        assertThat(johnDoe, hasProperty("name", equalTo("John Doe")));
        Person johnDoe2 = new Person("John Doe");
        assertThat(johnDoe, samePropertyValuesAs(johnDoe2));
    }

With this test, we can instantly look for property name and check it’s value and don’t have to use the getter. Also a small sidenote. We can also only use hasProperty, then it only checks that the value exists.

3. Custom Matcher

Right now there are 69 Implementations of matchers that you can use. Right now i want to show you some custom-matcher for palindromes.

Java
package org.codenest;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

public class IsPalindromeMatcher {
    public static Matcher<String> isPalindrome() {
        return new TypeSafeMatcher<String>() {
            @Override
            protected boolean matchesSafely(String item) {
                String reversed = new StringBuilder(item).reverse().toString();
                return item.equals(reversed);
            }

            @Override
            public void describeTo(Description description) {
                description.appendText("is a palindrome");
            }
        };
    }
}

String palindrome = "racecar";
String notPalindrome = "hello";

assertThat(palindrome, isPalindrome());
assertThat(notPalindrome, isPalindrome()); // This assertion will fail

Kommentar verfassen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Nach oben scrollen