junit

JUnit BaseMatcher Example

In this tutorial, we shall show users JUnit BaseMatcher Example. It is very common to test the matches in JUnit. It provides many inbuilt matchers for our testing.

We have seen in our previous tutorials how we can test our methods with the help of matchers.

In JUnit Hamcrest Example we have seen how JUnit matchers works. In this tutorial we will focus on BaseMatcher class of JUnit.
 
 
 
 
 

1. Introduction

BaseMatcher is the base class for all Matcher implementations. There is one point that is mentioned in API. Check the tip below.

Tip
We should not implement directly the Matcher class. Instead we should extend BaseMatcher class.

1.1 Class Hierarchy

This figure describes the class hierarchy of the BaseMatcher class. Boxes that are marked with orange are interfaces and those that are marked with blue are classes.

Class Hierarchy
Figure 1: Class Hierarchy

2. Technologies Used

We will be using the following technologies while creating this example.

  • Java 1.8
  • JUnit 4.12
  • Eclipse
  • Maven

3. Project Setup

Tip
You may skip project creation and jump directly to the beginning of the example below.

We will create a Maven project. Maven is a dependency management tool and helps us to get all required jar files for this example.
Open eclipse. Click on File -> New -> Maven Project.
Simply click on check mark as shown and click on the Next button.

JUnit BaseMatcher Example Setup 1
Figure 2: JUnit BaseMatcher Example Setup 1

On this screen fill in the required details as shown and click on the Finish button.

JUnit BaseMatcher Example Setup 2
Figure 3: JUnit BaseMatcher Example Setup 2

With the Finish button we are ready with the blank Maven project.

4. JUnit BaseMatcher Example

Before starting the programming part we need to change the pom.xml. Simply paste these lines in pom.xml.

pom.xml

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>junitbasematcher</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

Here in this file, we are simply adding a dependency for JUnit and also specifying that we need Java 8 for build and compilation.

4.1 Java classes

Let’s create a custom matcher by extending the BaseMatcher class.
This is a custom matcher that will test for a prime number.

IsPrime.java

package com.javacodegeeks;

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;

public class IsPrime<T> extends BaseMatcher<T> {

    @Override
    public boolean matches(Object actualValue) {
        return isPrime(actualValue);
    }

    @Override
    public void describeTo(Description description) {
        description.appendValue("Prime Number.");
    }

    @Override
    public void describeMismatch(Object item, Description description) {
        description.appendValue(item + " is not a Prime Number.");
    }

    private static boolean isPrime(Object actual) {
        if (actual == null) {
            return false;
        }

        if (actual instanceof Integer) {
            int num = ((Integer) actual).intValue();
            for (int i = 2; i <= num / 2; i++) {
                if (((Integer) actual).intValue() % i == 0) {
                    return false;
                }
            }
            return true;
        } else if (actual instanceof String) {
            try {
                int num = (Integer.valueOf((String) actual)).intValue();
                for (int i = 2; i <= num / 2; i++) {
                    if (num % i == 0) {
                        return false;
                    }
                }
                return true;
            } catch (NumberFormatException nfe) {
                return false;
            }
        }
        return false;
    }

    @Factory
    public static <T> Matcher<T> isPrime() {
        return new IsPrime<T>();
    }
}

Let’s analyze the above class and its methods. We have extended the BaseMatcher class (see line 8) to create our own Matcher.
Line 11: The matches() method will match for the condition. This method is overridden from Matcher interface. It evaluates the matcher for argument item.
Line 16: The describeTo() method will print the required description. This method is overridden from SelfDescribing interface. It will generate a description of the object.
Line 21: The describeMismatch() method will print a message when ever match is not fulfilled. This method is overridden from BaseMatcher class and it overrides from Matcher class. It will generate a description of why the matcher has not accepted the item.
Line 55: This is the main method that is called from outside the class. In return it will call matches() method which is written at line 11.

Next, we will create a test class to test out custom matcher.

IsPrimeTest.java

package com.javacodegeeks;

import static com.javacodegeeks.IsPrime.isPrime;
import static org.junit.Assert.assertThat;

import org.junit.Test;

public class IsPrimeTest {

    @Test
    public void testIsPrime() {
        assertThat(4, isPrime());
    }
}

Since the value 4 at line 12 is not a prime it will display a failure message like this:

Test Fail
Figure 4: Test Fail

It is clear that in class IsPrime above at line 16, we have defined a message. In Figure 4, we can see that message is showing as Expected: "Prime Number.".
Similarly failure message as defined at line 21 in class IsPrime is shown as but:"4 is not a Prime Number."
So, we can see that we have defined our own messages.

Otherwise, if we run with a value 2, which is a prime we will get a success.

Test Pass
Figure 5: Test Pass

5. Conclusion

We have learned about the class BaseMatcher of JUnit. It is very important class and works as a base class for many matchers in JUnit. We have seen how we can create our own custom matcher and we have also learned how to use it.

If you look into the classes of JUnit you will see the same behavior as described here. We have also learned that we should not directly implement the Matcher interface but extend the BaseMatcher class, which is of course an Abstract class.

6. Download the Eclipse Project

This is JUnit BaseMatcher Example.

Download
You can download the full source code of this example here: JUnitBaseMatcher.zip

Vinod Kumar Kashyap

Vinod is Sun Certified and love to work in Java and related technologies. Having more than 13 years of experience, he had developed software's including technologies like Java, Hibernate, Struts, Spring, HTML 5, jQuery, CSS, Web Services, MongoDB, AngularJS, AWS. He is also a JUG Leader of Chandigarh Java User Group.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button