View Javadoc

1   package com.atlassian.cache;
2   
3   import javax.annotation.Nonnull;
4   
5   import com.atlassian.util.concurrent.Supplier;
6   
7   import org.hamcrest.BaseMatcher;
8   import org.hamcrest.Description;
9   
10  /**
11   * Hamcrest matcher for statistics that recognizes the fact that they are optional.
12   *
13   * @since v2.4.0
14   */
15  public class StatisticMatcher extends BaseMatcher<Supplier<Long>>
16  {
17      public static StatisticMatcher stat(long expectedValue)
18      {
19          return new StatisticMatcher(expectedValue);
20      }
21  
22      private final long expectedValue;
23  
24      private StatisticMatcher(long expectedValue)
25      {
26          this.expectedValue = expectedValue;
27      }
28  
29      @Override
30      public boolean matches(Object o)
31      {
32          return o instanceof Supplier ? matches((Supplier<?>)o) : (o == null);
33      }
34  
35      private boolean matches(@Nonnull Supplier<?> supplier)
36      {
37          // Note: It is *not* okay for the supplier to return null!
38          final Object value = supplier.get();
39          return value instanceof Long && ((Long)value) == expectedValue;
40      }
41  
42      @Override
43      public void describeTo(Description description)
44      {
45          description.appendText("either null or a statistic with the value ").appendValue(expectedValue);
46      }
47  }