All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.carmatechnologies.commons.testing.matchers.ThrowableMatcher Maven / Gradle / Ivy

There is a newer version: 1.0.1
Show newest version
package com.carmatechnologies.commons.testing.matchers;

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

public class ThrowableMatcher extends TypeSafeMatcher {
    private final String expected;
    private String actual = "nothing";

    @Factory
    public static Matcher threw(final Class expected) {
        return new ThrowableMatcher(expected);
    }

    ThrowableMatcher(final Class expected) {
        this.expected = expected.getName();
    }

    @Override
    protected boolean matchesSafely(final Runnable action) {
        try {
            action.run();
            return false;
        } catch (Throwable t) {
            actual = t.getClass().getName();
            return expected.equals(actual);
        }
    }

    @Override
    public void describeTo(final Description description) {
        description.appendText("Should have thrown ").appendText(expected).appendText(" but threw ").appendText(actual).appendText(".");
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy