Coder Social home page Coder Social logo

junit-utils's Introduction

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

Examples

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),
        throwsException(NullPointerException.class));

To test the exception message, add withMessageContaining ...

assertThat(() -> myObject.doStuff(null),
        throwsException(NullPointerException.class)
            .withMessageContaining("ERR-120008"));

... or combine a String matcher:

assertThat(() -> agent.loadSchemaFile("bad-schema.xsd"),
        throwsException(AgentConfigurationException.class)
            .withMessage(
                either(startsWith("ERR-0001"))
                    .or(containsAny("invalid schema").ignoreCase())));

If required, you can also test the exception cause:

assertThat(() -> myObject.doStuff(null),
        throwsException(MyException.class).withMessageContaining("ERR-120008")
            .withCause(NullPointerException.class));

And more:

assertThat(() -> myObject.doStuff(null),
        throwsException(MyException.class).withMessageContaining("ERR-120008")
            .withCause(
                exception(NullPointerException.class)
                    .withMessage("stuff cannot be 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:

<dependency>
    <groupId>net.obvj</groupId>
    <artifactId>junit-utils</artifactId>
    <version>1.7.0</version>
</dependency>

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

junit-utils's People

Contributors

dependabot[bot] avatar oswaldobapvicjr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

dsenften

junit-utils's Issues

Combining different Matchers with the ExceptionMatcher

Enhancement

The purpose of this enhancement is to allow different matches in combination with the ExceptionMatcher, so that the following instructions could be possible:

assertThat(() -> AgentsXml.loadSchemaFile("testAgents/invalidSchema.xsd"),
                throwsException(AgentConfigurationException.class)
                    .withMessage(equalTo("Schema file not found")));
assertThat(() -> AgentsXml.loadSchemaFile("testAgents/invalidSchema.xsd"),
                throwsException(AgentConfigurationException.class)
                    .withMessage(either(startsWith("Invalid schema")).or(containsAny("agents.xml").ignoreCase())));

Additional details

  • The code shall be developed in the issue/0013 branch.

Quality criteria

The following criteria will be observed during the Code Review:

Code coverage

  • The produced code shall be secured by unit tests.
  • Test coverage shall remain the same (100%).

Documentation

  • All methods shall be documented with Javadoc, providing examples of usage.
  • Javadoc pages shall be compilable with no warnings

Enhance StringMatcher to accept any CharSequence

Purpose

The purpose of this enhancement is to upgrade the existing StringMatcher to accept any CharSequence, such as StringBuilder, CharBuffer, String, and other subtypes.

Additional details

  • The code shall be developed in the issue/0008 branch.

Quality criteria

The following criteria will be observed during the Code Review:

Code coverage

  • The produced code shall be secured by unit tests.
  • Test coverage shall remain the same (100%).

Documentation

  • All methods shall be documented with Javadoc, providing examples of usage.
  • Javadoc pages shall be compilable with no warnings

Improvement on the Javadoc of the StringMatcher class

Purpose

The method documentation for StringMatcher.ignoreCase() should provide an example of usage. For example:

assertThat("the quick brown fox", containsAny("FOX").ignoreCase())

Additional details

  • The code shall be developed in the issue/0007 branch.

Quality criteria

The following criteria will be observed during the Code Review:

Documentation

  • All methods shall be documented with Javadoc, providing examples of usage.
  • Javadoc pages shall be compilable with no warnings

Convert TestUtil.assertStringContains() to a Matcher object

Purpose

The purpose of this Pull Request is to implement a new Matcher object that executes the business logic implemented by the static methods TestUtil.assertStringContains() and TestUtil.assertStringDoesNotContain(), to allow the usage with org.hamcrest.MatcherAssert.assertThat() methods. These methods provide a more fluent manner to create JUnit tests.

Additional details

  • The code shall be developed in the issue/001 branch.
  • The new class StringMatchers shall be placed inside the (existing) package net.obvj.junit.utils.matchers.

Quality criteria

  • The produced code shall be secured by unit tests.
  • The code shall be revised by the Project Maintainer prior to acceptance.

Add ignore-case choice to the StringMatcher

Purpose

The purpose of this enhancement is to implement a choice to ignore the case of an examined string inside the existing StringMatcher.

Example:

     assertThat("The text", containsAll("the", "text").ignoreCase());

Additional details

  • The code shall be developed in the issue/0005 branch.

Quality criteria

The following criteria will be observed during Code Review:

Code coverage

  • The produced code shall be secured by unit tests.
  • Test coverage shall remain the same (100%).

Documentation

  • All methods shall be documented with Javadoc, providing examples of usage.
  • Javadoc pages shall be compilable with no warnings

Fix ExceptionMatcher to accept also subclasses of a given exception and cause

Problem details:

When trying the following instruction:

assertThat(() -> AgentsXml.loadSchemaFile("testAgents/invalidSchema.xsd"),
                throwsException(AgentConfigurationException.class).withCause(SAXException.class));

The assertion fails, with the following message:

java.lang.AssertionError: 
Expected: 
          net.obvj.smart.conf.AgentConfigurationException
          and cause: jdk.internal.org.xml.sax.SAXException
     but: 
          the cause was: org.xml.sax.SAXParseException

However, when using the classic TestUtils.assertException(...) method, the following assertion succeeds:

        assertException(AgentConfigurationException.class, null, SAXException.class,
                () -> AgentsXml.loadSchemaFile("testAgents/invalidSchema.xsd"));

Please note that SAXParseException is a child of SAXException.

Additional details

  • The code shall be developed in the issue/0009 branch.

Quality criteria

The following criteria will be observed during the Code Review:

Code coverage

  • The produced code shall be secured by unit tests.
  • Test coverage shall remain the same (100%).

Documentation

  • All methods shall be documented with Javadoc, providing examples of usage.
  • Javadoc pages shall be compilable with no warnings

Allow testing functions that throw checked exceptions

Is your feature request related to a problem? Please describe.

Currently, the ExceptionMatcher cannot accept a function that throws a checked exception.

For example, the following assertion cannot be compiled due to the following error: "Unhandled exception type ParseException"

        assertThat(() -> {
            throw new ParseException(new IllegalArgumentException(ROOT_CAUSE_MESSAGE1),
                    DETAILED_MESSAGE1);
        },
        throwsException(ParseException.class)
                .withMessage(DETAILED_MESSAGE1)
                .withCause(IllegalArgumentException.class));

The above assertion works fine if the ParseException is unchecked (child of RuntimeException).
This is because the ExceptionMatcher, returned by throwsException() accepts a Runnable.

Describe the solution you'd like

I want the possibility to test checked and unchecked exceptions the same way.

It seems to be achievable by replacing the Runnable with an Executable, like this:

public interface Executable {
	void execute() throws Exception;
}

Describe alternatives you've considered
Using JUnit 5 assertThrows could be an alternative, but it doesn't have a fluent API to assert the message and cause in a fancy way that junit-utils does.

Additional context

N/A

issue/0018: New AdvancedMatchers class

Enhancement

Background

It may be hard for developers to remember all matcher classes. It would be better to have a single entry-point, to which the API users could access all Matchers with a single static import declaration.

Proposed solution

Introduce a new class AdvancedMatchers with static methods providing instances of all Matchers available, similar to Hamcrest's CoreMatchers class.

Example of usage:

import static net.obvj.junit.utils.matchers.AdvancedMatchers.*;

public class MyClassTest
{
    @Test
    public void testNoInstancesAllowed()
    {
        assertThat(MyClass.class, noInstancesAllowed().withMessage("Utility class"));
    }
}

Additional details

  • The code shall be developed in the issue/0018 branch.

Quality criteria

The following criteria will be observed during the Code Review:

Code coverage

  • The produced code shall be secured by unit tests.
  • Test coverage shall remain the same (100%).

Documentation

  • All methods shall be documented with Javadoc, providing examples of usage.
  • Javadoc pages shall be compilable with no warnings

issue/0016: Combine the ExceptionMatcher inside InstantiationNotAllowedMatcher

Enhancement

The purpose of this enhancement is to allow the combination of an ExceptionMatcher inside InstantiationNotAllowed so that the following instructions could be possible:

assertThat(AgentsXml.class, instantiationNotAllowed()
                .throwing(IllegalStateException.class));
assertThat(AgentsXml.class, instantiationNotAllowed()
                .throwing(IllegalStateException.class)
                    .withMessage(equalTo("Utility class"))));

Additional details

  • The code shall be developed in the issue/0016 branch.

Quality criteria

The following criteria will be observed during the Code Review:

Code coverage

  • The produced code shall be secured by unit tests.
  • Test coverage shall remain the same (100%).

Documentation

  • All methods shall be documented with Javadoc, providing examples of usage.
  • Javadoc pages shall be compilable with no warnings

New IsPositive/IsNegative matchers

Enhancement

Proposed solution

Introduce a new matchers "AdvancedMatchers.isPostitive()/isNegative().

Example of usage:

import static net.obvj.junit.utils.matchers.AdvancedMatchers.*;

public class MyClassTest
{
    @Test
    public void testNoInstancesAllowed()
    {
        assertThat(-100.5, isNegative());
        assertThat(SystemUtils.getCurrentTimeNano(), isPositive());
    }
}

Additional details

  • The code shall be developed in the issue/0020 branch.

Quality criteria

The following criteria will be observed during the Code Review:

Code coverage

  • The produced code shall be secured by unit tests.
  • Test coverage shall remain the same (100%).

Documentation

  • All methods shall be documented with Javadoc, providing examples of usage.
  • Javadoc pages shall be compilable with no warnings

Create ExceptionMatcher

Purpose

The purpose of this enhancement is to implement a new Matcher object that executes the business logic implemented by the existing static methods TestUtil.assertException(..), to allow assertions using org.hamcrest.MatcherAssert.assertThat() methods, and providing a more fluent manner to create JUnit tests.

The matcher shall allow evaluation of exception class, message, and cause, by providing a fluent interface in which expected behaviors can be set by chained method calls.

Example:

     assertThat(() -> obj.doStuff(null),
              throwsException(IllegalArgumentException.class)
                  .withMessageContaining("argument cannot be null")
                  .withCause(NullPointerException.class));

Additional details

  • The code shall be developed in the issue/0003 branch.
  • The new class ExceptionMatcher shall be placed inside the (existing) package net.obvj.junit.utils.matchers.

Quality criteria

The following criteria will be observed during Code Review:

Code coverage

  • The produced code shall be secured by unit tests.
  • Test coverage shall remain the same (100%).

Documentation

  • All methods shall be documented with Javadoc, providing examples of usage.
  • Javadoc pages shall be compilable with no warnings

New ExceptionMatchers: throwsException() and throwsNoException()

Enhancement

Proposed solution

Introduce new methods for checking that a procedure throws any or no Exception.

Example of usage:

        assertThat(() -> myMethod(), throwsException()); // any Exception
        assertThat(() -> myMethod(), throwsNoException()); // no Exception

Additional details

  • The code shall be developed in the issue/0022 branch.

Quality criteria

The following criteria will be observed during the Code Review:

Code coverage

  • The produced code shall be secured by unit tests.
  • Test coverage shall remain the same (100%).

Documentation

  • All methods shall be documented with Javadoc, providing examples of usage.
  • Javadoc pages shall be compilable with no warnings

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.