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

org.hamcrest.core.CombinableMatcher Maven / Gradle / Ivy

There is a newer version: 2.12.15
Show newest version
package org.hamcrest.core;

import org.hamcrest.*;

import java.util.ArrayList;

public class CombinableMatcher extends TypeSafeDiagnosingMatcher {
  private final Matcher matcher;

  public CombinableMatcher(Matcher matcher) {
    this.matcher = matcher;
  }

  @Override
  protected boolean matchesSafely(T item, Description mismatch) {
    if (!matcher.matches(item)) {
      matcher.describeMismatch(item, mismatch);
      return false;
    }
    return true;
  }

  @Override
  public void describeTo(Description description) {
    description.appendDescriptionOf(matcher);
  }

  public CombinableMatcher and(Matcher other) {
    return new CombinableMatcher(new AllOf(templatedListWith(other)));
  }

  public CombinableMatcher or(Matcher other) {
    return new CombinableMatcher(new AnyOf(templatedListWith(other)));
  }

  private ArrayList> templatedListWith(Matcher other) {
    ArrayList> matchers = new ArrayList>();
    matchers.add(matcher);
    matchers.add(other);
    return matchers;
  }

  /**
   * Creates a matcher that matches when both of the specified matchers match the examined object.
   * 

* For example: *

assertThat("fab", both(containsString("a")).and(containsString("b")))
*/ @Factory public static CombinableBothMatcher both(Matcher matcher) { return new CombinableBothMatcher(matcher); } public static final class CombinableBothMatcher { private final Matcher first; public CombinableBothMatcher(Matcher matcher) { this.first = matcher; } public CombinableMatcher and(Matcher other) { return new CombinableMatcher(first).and(other); } } /** * Creates a matcher that matches when either of the specified matchers match the examined object. *

* For example: *

assertThat("fan", either(containsString("a")).and(containsString("b")))
*/ @Factory public static CombinableEitherMatcher either(Matcher matcher) { return new CombinableEitherMatcher(matcher); } public static final class CombinableEitherMatcher { private final Matcher first; public CombinableEitherMatcher(Matcher matcher) { this.first = matcher; } public CombinableMatcher or(Matcher other) { return new CombinableMatcher(first).or(other); } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy