View Javadoc
1   /*
2    * Copyright 2019 SPF4J.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.spf4j.test.matchers;
17  
18  import java.util.function.Predicate;
19  import org.hamcrest.Description;
20  import org.hamcrest.Matcher;
21  import org.hamcrest.TypeSafeMatcher;
22  
23  /**
24   *
25   * @author Zoltan Farkas
26   */
27  public final class PredicateMatcher<T> extends TypeSafeMatcher<T> {
28  
29    private final Predicate<T> predicate;
30  
31    public PredicateMatcher(final Predicate<T> predicate) {
32      this.predicate = predicate;
33    }
34  
35    @Override
36    protected boolean matchesSafely(final T item) {
37      return predicate.test(item);
38    }
39  
40    @Override
41    public void describeTo(final Description description) {
42      description.appendText("a object testing positively for '" + predicate + "'");
43    }
44  
45    public static <T> Matcher<T> matchesPredicate(final Predicate<T> pred) {
46      return new PredicateMatcher<>(pred);
47    }
48  
49  }