001/**
002 * Copyright (C) 2011 rwoo@gmx.de
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *         http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package com.googlecode.catchexception.throwable.apis.internal.hamcrest;
017
018import org.hamcrest.BaseMatcher;
019import org.hamcrest.CoreMatchers;
020import org.hamcrest.Description;
021import org.hamcrest.Matcher;
022
023/**
024 * 
025 * Creates a {@link Matcher matcher} that matches an throwable with a certain
026 * message.
027 * 
028 * @author rwoo
029 * 
030 * @param <T>
031 *            an throwable subclass
032 */
033public class ThrowableMessageMatcher<T extends Throwable> extends
034        BaseMatcher<T> {
035
036    /**
037     * The string matcher that shall match throwable message.
038     */
039    private Matcher<String> expectedMessageMatcher;
040
041    /**
042     * @param expectedMessage
043     *            the expected throwable message
044     */
045    public ThrowableMessageMatcher(String expectedMessage) {
046        super();
047        this.expectedMessageMatcher = CoreMatchers.is(expectedMessage);
048    }
049
050    /**
051     * @param expectedMessageMatcher
052     *            a string matcher that shall match the throwable message
053     */
054    public ThrowableMessageMatcher(Matcher<String> expectedMessageMatcher) {
055        super();
056
057        this.expectedMessageMatcher = expectedMessageMatcher;
058    }
059
060    /*
061     * (non-Javadoc)
062     * 
063     * @see org.hamcrest.Matcher#matches(java.lang.Object)
064     */
065    public boolean matches(Object obj) {
066        if (!(obj instanceof Throwable))
067            return false;
068
069        Throwable throwable = (Throwable) obj;
070
071        String foundMessage = throwable.getMessage();
072
073        return expectedMessageMatcher.matches(foundMessage);
074    }
075
076    /*
077     * (non-Javadoc)
078     * 
079     * @see org.hamcrest.SelfDescribing#describeTo(org.hamcrest.Description)
080     */
081    public void describeTo(Description description) {
082        description.appendText("has a message that ").appendDescriptionOf(
083                expectedMessageMatcher);
084    }
085
086}