Skip to content


Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Latest commit


Git stats


Failed to load latest commit information.
Latest commit message
Commit time

junit-utils logo

Known Vulnerabilities GitHub Workflow Status Coverage Maven Central Javadoc

Common utilities for working with JUnit:

  • assertion of exceptions, as well as exception details, such as message and cause
  • assertion of strings contents
  • testing that a class cannot be instantiated


Note: Consider the following static import declarations for readability:

import static net.obvj.junit.utils.matchers.AdvancedMatchers.*;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;

Asserting exceptions

The following assertion is true if the examined method throws a NullPointerException:

assertThat(() -> myObject.doStuff(null),

To test the exception message, add withMessageContaining ...

assertThat(() -> myObject.doStuff(null),

... or combine a String matcher:

assertThat(() -> agent.loadSchemaFile("bad-schema.xsd"),
                    .or(containsAny("invalid schema").ignoreCase())));

If required, you can also test the exception cause:

assertThat(() -> myObject.doStuff(null),

Testing that instantiation is not allowed

The following assertion is particularly useful for utility classes:

assertThat(TestUtils.class, instantiationNotAllowed());

A matching class shall have all constructors declared as private and throw an exception inside the default constructor.

Testing the contents of a string

The following examples represent some successful assertions using the Advanced String matcher:

assertThat("The quick brown fox jumps over the lazy dog", containsAll("fox", "dog"));
assertThat("The quick brown fox jumps over the lazy dog", containsAny("FOX", "dragon").ignoreCase());
assertThat("The quick brown fox jumps over the lazy dog", containsNone("centaur"));

Testing numbers

Sometimes, it's more meaningful to check whether a number is positive or negative than testing the value itself, especially in situations where the exact value is unpredictable:

assertThat(stopwatch.elapsedTime(),           isPositive());
assertThat(duration.compareTo(otherDuration), isNegative());

How to include it

If you are using Maven, add junit-utils as a dependency in your pom.xml file:


If you use other dependency management systems (such as Gradle, Grape, Ivy, etc.) click here.