All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.lyncode.test.matchers.builder.AbstractMatcherBuilder Maven / Gradle / Ivy

/**
 * Copyright 2012 Lyncode
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.lyncode.test.matchers.builder;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.hamcrest.internal.ReflectiveTypeFinder;

import java.util.ArrayList;
import java.util.List;

import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.core.AllOf.allOf;

public abstract class AbstractMatcherBuilder implements MatcherBuilder {
    private static final ReflectiveTypeFinder TYPE_FINDER = new ReflectiveTypeFinder("matchesSafely", 1, 0);
    private TypeSafeMatcher typeSafeMatcher = getTypeSafeMatcher();
    private List> matchers = new ArrayList>();

    public AbstractMatcherBuilder(Matcher... matchers) {
        add(matchers);
    }

    public AbstractMatcherBuilder add (Matcher... matchers) {
        this.matchers.addAll(asList(matchers));
        return this;
    }

    @Override
    public Matcher build() {
        if (matchers.isEmpty())
            return instanceOf(getParameterClass());
        else if (matchers.size() == 1)
            return matchers.get(0);
        return allOf(matchers.toArray(new Matcher[matchers.size()]));
    }

    public Class getParameterClass() {
        return TYPE_FINDER.findExpectedType(typeSafeMatcher.getClass());
    }


    private TypeSafeMatcher getTypeSafeMatcher() {
        return new TypeSafeMatcher() {
            @Override
            protected boolean matchesSafely(T item) {
                return true;
            }

            @Override
            public void describeTo(Description description) {

            }
        };
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy