How to use TypeSafeMatcher class of org.hamcrest package

Best junit code snippet using org.hamcrest.TypeSafeMatcher

Run junit automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package org.incode.module.base;
2
3import java.io.File;
4import java.io.IOException;
5import java.util.Arrays;
6import java.util.List;
7import org.hamcrest.CoreMatchers;
8import org.hamcrest.Description;
9import org.hamcrest.Factory;
10import org.hamcrest.Matcher;
11import org.hamcrest.Matchers;
12import org.hamcrest.TypeSafeMatcher;
13import org.hamcrest.core.IsEqual;
14import org.hamcrest.core.StringContains;
15import org.hamcrest.core.StringEndsWith;
16import org.hamcrest.core.StringStartsWith;
17import org.apache.isis.core.commons.lang.StringExtensions;
18
19import static org.hamcrest.CoreMatchers.nullValue;
20
21/**
22 * Hamcrest {@link org.hamcrest.Matcher} implementations.
23 * 
24 */
25public final class IsisMatchers {
26
27    private IsisMatchers() {
28    }
29
30    @Factory
31    public static Matcher<String> containsStripNewLines(final String expected) {
32        final String strippedExpected = StringExtensions.stripNewLines(expected);
33        return new StringContains(strippedExpected) {
34            @Override
35            public boolean matchesSafely(final String actual) {
36                return super.matchesSafely(StringExtensions.stripNewLines(actual));
37            }
38
39            @Override
40            public void describeTo(final Description description) {
41                description.appendText("a string (ignoring new lines) containing").appendValue(strippedExpected);
42            }
43        };
44    }
45
46    @Factory
47    public static Matcher<String> equalToStripNewLines(final String expected) {
48        final String strippedExpected = StringExtensions.stripNewLines(expected);
49        return new IsEqual<String>(strippedExpected) {
50            @Override
51            public boolean matches(final Object actualObj) {
52                final String actual = (String) actualObj;
53                return super.matches(StringExtensions.stripNewLines(actual));
54            }
55
56            @Override
57            public void describeTo(final Description description) {
58                description.appendText("a string (ignoring new lines) equal to").appendValue(strippedExpected);
59            }
60        };
61    }
62
63    @Factory
64    public static StringStartsWith startsWithStripNewLines(final String expected) {
65        final String strippedExpected = StringExtensions.stripNewLines(expected);
66        return new StringStartsWith(strippedExpected) {
67            @Override
68            public boolean matchesSafely(final String actual) {
69                return super.matchesSafely(StringExtensions.stripNewLines(actual));
70            }
71
72            @Override
73            public void describeTo(final Description description) {
74                description.appendText("a string (ignoring new lines) starting with").appendValue(strippedExpected);
75            }
76        };
77    }
78
79    @Factory
80    public static Matcher<String> endsWithStripNewLines(final String expected) {
81        final String strippedExpected = StringExtensions.stripNewLines(expected);
82        return new StringEndsWith(strippedExpected) {
83            @Override
84            public boolean matchesSafely(final String actual) {
85                return super.matchesSafely(StringExtensions.stripNewLines(actual));
86            }
87
88            @Override
89            public void describeTo(final Description description) {
90                description.appendText("a string (ignoring new lines) ending with").appendValue(strippedExpected);
91            }
92        };
93    }
94
95    @Factory
96    public static <T> Matcher<T> anInstanceOf(final Class<T> expected) {
97        return new TypeSafeMatcher<T>() {
98            @Override
99            public boolean matchesSafely(final T actual) {
100                return expected.isAssignableFrom(actual.getClass());
101            }
102
103            @Override
104            public void describeTo(final Description description) {
105                description.appendText("an instance of ").appendValue(expected);
106            }
107        };
108    }
109
110    @Factory
111    public static Matcher<String> nonEmptyString() {
112        return new TypeSafeMatcher<String>() {
113            @Override
114            public boolean matchesSafely(final String str) {
115                return str != null && str.length() > 0;
116            }
117
118            @Override
119            public void describeTo(final Description description) {
120                description.appendText("a non empty string");
121            }
122
123        };
124    }
125
126    @Factory
127    @SuppressWarnings("unchecked")
128    public static Matcher<String> nonEmptyStringOrNull() {
129        return CoreMatchers.anyOf(nullValue(String.class), nonEmptyString());
130    }
131
132    @Factory
133    public static Matcher<List<?>> containsElementThat(final Matcher<?> elementMatcher) {
134        return new TypeSafeMatcher<List<?>>() {
135            @Override
136            public boolean matchesSafely(final List<?> list) {
137                for (final Object o : list) {
138                    if (elementMatcher.matches(o)) {
139                        return true;
140                    }
141                }
142                return false;
143            }
144
145            @Override
146            public void describeTo(final Description description) {
147                description.appendText("contains element that ").appendDescriptionOf(elementMatcher);
148            }
149        };
150    }
151
152    @Factory
153    public static <T extends Comparable<T>> Matcher<T> greaterThan(final T c) {
154        return Matchers.greaterThan(c);
155    }
156
157    @Factory
158    public static Matcher<Class<?>> classEqualTo(final Class<?> operand) {
159
160        class ClassEqualsMatcher extends TypeSafeMatcher<Class<?>> {
161            private final Class<?> clazz;
162
163            public ClassEqualsMatcher(final Class<?> clazz) {
164                this.clazz = clazz;
165            }
166
167            @Override
168            public boolean matchesSafely(final Class<?> arg) {
169                return clazz == arg;
170            }
171
172            @Override
173            public void describeTo(final Description description) {
174                description.appendValue(clazz);
175            }
176        }
177
178        return new ClassEqualsMatcher(operand);
179    }
180
181    @Factory
182    public static Matcher<File> existsAndNotEmpty() {
183
184        return new TypeSafeMatcher<File>() {
185
186            @Override
187            public void describeTo(final Description arg0) {
188                arg0.appendText("exists and is not empty");
189            }
190
191            @Override
192            public boolean matchesSafely(final File f) {
193                return f.exists() && f.length() > 0;
194            }
195        };
196    }
197
198    @Factory
199    public static Matcher<String> matches(final String regex) {
200        return new TypeSafeMatcher<String>() {
201
202            @Override
203            public void describeTo(final Description description) {
204                description.appendText("string matching " + regex);
205            }
206
207            @Override
208            public boolean matchesSafely(final String str) {
209                return str.matches(regex);
210            }
211        };
212    }
213
214    @Factory
215    public static <X> Matcher<Class<X>> anySubclassOf(final Class<X> cls) {
216        return new TypeSafeMatcher<Class<X>>() {
217
218            @Override
219            public void describeTo(final Description arg0) {
220                arg0.appendText("is subclass of ").appendText(cls.getName());
221            }
222
223            @Override
224            public boolean matchesSafely(final Class<X> item) {
225                return cls.isAssignableFrom(item);
226            }
227        };
228    }
229
230    @Factory
231    public static <T> Matcher<List<T>> sameContentsAs(final List<T> expected) {
232        return new TypeSafeMatcher<List<T>>() {
233
234            @Override
235            public void describeTo(final Description description) {
236                description.appendText("same sequence as " + expected);
237            }
238
239            @Override
240            public boolean matchesSafely(final List<T> actual) {
241                return actual.containsAll(expected) && expected.containsAll(actual);
242            }
243        };
244    }
245
246    @Factory
247    public static <T> Matcher<List<T>> listContaining(final T t) {
248        return new TypeSafeMatcher<List<T>>() {
249    
250            @Override
251            public void describeTo(Description arg0) {
252                arg0.appendText("list containing ").appendValue(t);
253            }
254    
255            @Override
256            public boolean matchesSafely(List<T> arg0) {
257                return arg0.contains(t);
258            }
259        };
260    }
261
262    @Factory
263    public static <T> Matcher<List<T>> listContainingAll(final T... items) {
264        return new TypeSafeMatcher<List<T>>() {
265
266            @Override
267            public void describeTo(Description arg0) {
268                arg0.appendText("has items ").appendValue(items);
269                
270            }
271
272            @Override
273            public boolean matchesSafely(List<T> arg0) {
274                return arg0.containsAll(Arrays.asList(items));
275            }
276        };
277    }
278
279    @Factory
280    public static Matcher<List<Object>> containsObjectOfType(final Class<?> cls) {
281        return new TypeSafeMatcher<List<Object>>() {
282
283            @Override
284            public void describeTo(final Description desc) {
285                desc.appendText("contains instance of type " + cls.getName());
286            }
287
288            @Override
289            public boolean matchesSafely(final List<Object> items) {
290                for (final Object object : items) {
291                    if (cls.isAssignableFrom(object.getClass())) {
292                        return true;
293                    }
294                }
295                return false;
296            }
297        };
298    }
299
300    @Factory
301    public static Matcher<String> startsWith(final String expected) {
302        return new TypeSafeMatcher<String>() {
303
304            @Override
305            public void describeTo(Description description) {
306                description.appendText(" starts with '" + expected + "'");
307            }
308
309            @Override
310            public boolean matchesSafely(String actual) {
311                return actual.startsWith(expected);
312            }
313        };
314    }
315
316    @Factory
317    public static Matcher<String> contains(final String expected) {
318        return new TypeSafeMatcher<String>() {
319
320            @Override
321            public void describeTo(Description description) {
322                description.appendText(" contains '" + expected + "'");
323            }
324
325            @Override
326            public boolean matchesSafely(String actual) {
327                return actual.contains(expected);
328            }
329        };
330    }
331
332    
333    @Factory
334    public static Matcher<File> equalsFile(final File file) throws IOException {
335        final String canonicalPath = file.getCanonicalPath();
336        return new TypeSafeMatcher<File>() {
337
338            @Override
339            public void describeTo(Description arg0) {
340                arg0.appendText("file '" + canonicalPath + "'");
341            }
342
343            @Override
344            public boolean matchesSafely(File arg0) {
345                try {
346                    return arg0.getCanonicalPath().equals(canonicalPath);
347                } catch (IOException e) {
348                    return false;
349                }
350            }
351        };
352    }
353
354}
355
Full Screen
copy
1package org.junit.internal.matchers;
2
3import java.lang.Throwable;
4import org.hamcrest.Description;
5import org.hamcrest.Factory;
6import org.hamcrest.Matcher;
7import org.hamcrest.TypeSafeMatcher;
8
9public class ThrowableMessageMatcher<T extends Throwable> extends TypeSafeMatcher<T> {
10    private final Matcher<String> matcher;
11
12    /* JADX DEBUG: Failed to find minimal casts for resolve overloaded methods, cast all args instead
13     method: MutableMD:(java.lang.Throwable, org.hamcrest.Description):void
14     arg types: [T, org.hamcrest.Description]
15     candidates:
16      org.junit.internal.matchers.ThrowableMessageMatcher.describeMismatchSafely(java.lang.Object, org.hamcrest.Description):void
17      MutableMD:(java.lang.Object, org.hamcrest.Description):void
18      MutableMD:(java.lang.Throwable, org.hamcrest.Description):void */
19    /* access modifiers changed from: protected */
20    @Override // org.hamcrest.TypeSafeMatcher
21    public /* bridge */ /* synthetic */ void describeMismatchSafely(Object obj, Description description) {
22        describeMismatchSafely((Throwable) ((Throwable) obj), description);
23    }
24
25    /* access modifiers changed from: protected */
26    @Override // org.hamcrest.TypeSafeMatcher
27    public /* bridge */ /* synthetic */ boolean matchesSafely(Object obj) {
28        return matchesSafely((Throwable) ((Throwable) obj));
29    }
30
31    public ThrowableMessageMatcher(Matcher<String> matcher2) {
32        this.matcher = matcher2;
33    }
34
35    @Override // org.hamcrest.SelfDescribing
36    public void describeTo(Description description) {
37        description.appendText("exception with message ");
38        description.appendDescriptionOf(this.matcher);
39    }
40
41    /* access modifiers changed from: protected */
42    public boolean matchesSafely(T item) {
43        return this.matcher.matches(item.getMessage());
44    }
45
46    /* access modifiers changed from: protected */
47    public void describeMismatchSafely(T item, Description description) {
48        description.appendText("message ");
49        this.matcher.describeMismatch(item.getMessage(), description);
50    }
51
52    @Factory
53    public static <T extends Throwable> Matcher<T> hasMessage(Matcher<String> matcher2) {
54        return new ThrowableMessageMatcher(matcher2);
55    }
56}
57
Full Screen
copy
1@Test(expected = NullPointerException.class)
2
Full Screen
copy
1    <dependency>
2        <groupId>org.hamcrest</groupId>
3        <artifactId>hamcrest-core</artifactId>
4        <version>1.3</version>
5        <scope>test</scope>
6    </dependency>
7
Full Screen
copy
1public class MyClass<E> {
2    private final Class<E> realType;
3    public MyClass(Class<E> realType) {
4        this.realType = realType;
5    }
6    public boolean Contains(Object o) {
7        E e = realType.cast(o); // runtime cast - will throw ClassCastException.
8        // Could also use realType.isInstance(o)
9        // or realType.isAssignableFrom(o.getClass())
10        ...
11    }
12}
13
Full Screen
copy
1new MyClass<MyObject>(MyObject.class)
2
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in TypeSafeMatcher

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)