View Javadoc
1   /*
2    * Copyright 2011-2024 the original author or authors.
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    *         https://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 com.googlecode.catchexception.throwable.apis.internal.hamcrest;
17  
18  import org.hamcrest.BaseMatcher;
19  import org.hamcrest.CoreMatchers;
20  import org.hamcrest.Description;
21  import org.hamcrest.Matcher;
22  
23  /**
24   * Creates a {@link Matcher matcher} that matches an throwable with a certain message.
25   *
26   * @param <T>
27   *            an throwable subclass
28   */
29  public class ThrowableMessageMatcher<T extends Throwable> extends BaseMatcher<T> {
30  
31      /**
32       * The string matcher that shall match throwable message.
33       */
34      private Matcher<String> expectedMessageMatcher;
35  
36      /**
37       * Instantiates a new throwable message matcher.
38       *
39       * @param expectedMessage
40       *            the expected throwable message
41       */
42      public ThrowableMessageMatcher(String expectedMessage) {
43          this.expectedMessageMatcher = CoreMatchers.is(expectedMessage);
44      }
45  
46      /**
47       * Instantiates a new throwable message matcher.
48       *
49       * @param expectedMessageMatcher
50       *            a string matcher that shall match the throwable message
51       */
52      public ThrowableMessageMatcher(Matcher<String> expectedMessageMatcher) {
53          this.expectedMessageMatcher = expectedMessageMatcher;
54      }
55  
56      @Override
57      public boolean matches(Object obj) {
58          if (!(obj instanceof Throwable)) {
59              return false;
60          }
61  
62          var throwable = (Throwable) obj;
63  
64          var foundMessage = throwable.getMessage();
65  
66          return expectedMessageMatcher.matches(foundMessage);
67      }
68  
69      @Override
70      public void describeTo(Description description) {
71          description.appendText("has a message that ").appendDescriptionOf(expectedMessageMatcher);
72      }
73  
74  }