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

org.cthul.matchers.object.InstanceOf Maven / Gradle / Ivy

Go to download

Provides hamcrest.org matchers for strings and exceptions, allows matching code blocks, and provides several utilities for combining matchers.

The newest version!
package org.cthul.matchers.object;

import org.cthul.matchers.chain.AndChainMatcher;
import org.cthul.matchers.diagnose.QuickDiagnosingMatcherBase;
import org.hamcrest.*;
import org.hamcrest.core.Is;
import org.hamcrest.core.IsInstanceOf;

/**
 * Example:
 * 
{@code 
 *   Object o = "foobar;
 *   assertThat(o, isA(String.class).thatIs(foo()).and(bar());
 * }
*/ public class InstanceOf extends QuickDiagnosingMatcherBase { private boolean prependIs; private final Class clazz; private IsInstanceOf matcher = null; public InstanceOf(boolean prependIs, Class expectedClass) { this.prependIs = prependIs; this.clazz = expectedClass; } public InstanceOf(Class expectedClass) { this(false, expectedClass); } protected IsInstanceOf matcher() { if (matcher == null) { matcher = new IsInstanceOf(clazz); } return matcher; } @Override public boolean matches(Object o) { return matcher().matches(o); } @Override public boolean matches(Object item, Description mismatch) { return quickMatch(matcher(), item, mismatch); } @Override public void describeMismatch(Object item, Description description) { //if (prependIs) description.appendText("was "); matcher().describeMismatch(item, description); } @Override public void describeTo(Description description) { if (prependIs) description.appendText("is "); matcher().describeTo(description); } public AndChainMatcher.Builder that(Matcher m) { if (prependIs) { return InstanceThat.isInstanceThat(clazz, m); } else { return InstanceThat.instanceThat(clazz, m); } } public AndChainMatcher.Builder thatIs(Matcher m) { return that(Is.is(m)); } @SuppressWarnings("unchecked") public Matcher that(Matcher... m) { if (prependIs) { return InstanceThat.isInstanceThat(clazz, m); } else { return InstanceThat.instanceThat(clazz, m); } } @Factory public static InstanceOf isInstanceOf(Class clazz) { return new InstanceOf<>(true, clazz); } @Factory public static InstanceOf instanceOf(Class clazz) { return new InstanceOf<>(clazz); } @Factory public static InstanceOf isA(Class clazz) { return new InstanceOf<>(true, clazz); } @Factory public static InstanceOf _instanceOf(Class clazz) { return new InstanceOf<>(clazz); } @Factory public static InstanceOf _isA(Class clazz) { return new InstanceOf<>(true, clazz); } @Factory public static InstanceOf a(Class clazz) { return new InstanceOf<>(clazz); } }