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.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 exception with a certain
026 * message.
027 * 
028 * @author rwoo
029 * 
030 * @param <T>
031 *            an exception subclass
032 */
033public class ExceptionMessageMatcher<T extends Exception> extends
034        BaseMatcher<T> {
035
036    /**
037     * The string matcher that shall match exception message.
038     */
039    private Matcher<String> expectedMessageMatcher;
040
041    /**
042     * @param expectedMessage
043     *            the expected exception message
044     */
045    public ExceptionMessageMatcher(String expectedMessage) {
046        super();
047        this.expectedMessageMatcher = CoreMatchers.is(expectedMessage);
048    }
049
050    /**
051     * @param expectedMessageMatcher
052     *            a string matcher that shall match the exception message
053     */
054    public ExceptionMessageMatcher(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 Exception))
067            return false;
068
069        Exception exception = (Exception) obj;
070
071        String foundMessage = exception.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}