1 package com.atlassian.cache.impl;
2
3 import com.atlassian.cache.CacheEntryEvent;
4
5 import org.hamcrest.BaseMatcher;
6 import org.hamcrest.Description;
7 import org.hamcrest.Matcher;
8
9 import static com.google.common.base.Objects.equal;
10 import static org.mockito.hamcrest.MockitoHamcrest.argThat;
11
12 public class CacheEntryEventMatcher<K, V> extends BaseMatcher<CacheEntryEvent<K, V>>
13 {
14 private final K key;
15 private final V value;
16 private final V oldValue;
17
18 private CacheEntryEventMatcher(K key, V value, V oldValue)
19 {
20 this.key = key;
21 this.value = value;
22 this.oldValue = oldValue;
23 }
24
25 @Override
26 public boolean matches(Object item)
27 {
28 return match(item) == null;
29 }
30
31 @Override
32 public void describeMismatch(Object item, Description description)
33 {
34 String match = match(item);
35 if (match != null)
36 {
37 description.appendText(match);
38 }
39 }
40
41 @Override
42 public void describeTo(Description description)
43 {
44 description.appendText(String.format("CacheEntryEvent(%s, %s, %s)", key, value, oldValue));
45 }
46
47 private String match(Object item)
48 {
49 if (! (item instanceof CacheEntryEvent))
50 {
51 return String.format("Not instance of CacheEntryEvent. Was: %s", item.getClass());
52 }
53
54 CacheEntryEvent<K, V> event = (CacheEntryEvent) item;
55 if (!equal(key, event.getKey()))
56 {
57 return String.format("Different keys expected %s, actual %s", key, event.getKey());
58 }
59 if (!equal(value, event.getValue()))
60 {
61 return String.format("Different values expected %s, actual %s", value, event.getValue());
62 }
63 if (!equal(oldValue, event.getOldValue()))
64 {
65 return String.format("Different old values expected %s, actual %s", oldValue, event.getOldValue());
66 }
67
68 return null;
69 }
70
71 public static <K, V> Matcher<CacheEntryEvent<K, V>> eventMatcher(K key, V value, V oldValue)
72 {
73 return new CacheEntryEventMatcher<K, V>(key, value, oldValue);
74 }
75
76 public static CacheEntryEvent event(Object key, Object value, Object oldValue)
77 {
78 return argThat(eventMatcher(key, value, oldValue));
79 }
80 }