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