hamcrest-compose icon indicating copy to clipboard operation
hamcrest-compose copied to clipboard

Add compose matcher builder

Open dtandersen opened this issue 4 years ago • 1 comments
trafficstars

Been using this builder based on your library for a few years and thought I'd share it.

import static org.hamcrest.Matchers.equalTo;
import static org.hobsoft.hamcrest.compose.ComposeMatchers.hasFeature;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import org.hamcrest.Matcher;
import org.hobsoft.hamcrest.compose.ComposeMatchers;

public class ComposeBuilder<T>
{
	private String compositeDescription;

	private final List<Matcher<T>> matchers = new ArrayList<>();

	public ComposeBuilder<T> withDescription(final String compositeDescription)
	{
		this.compositeDescription = compositeDescription;
		return this;
	}

	public <U> ComposeBuilder<T> withFeature(
			final String featureName,
			final Function<T, U> featureFunction,
			final Matcher<? super U> featureMatcher)
	{
		final Matcher<T> matcher = hasFeature(featureName, featureFunction, featureMatcher);
		matchers.add(matcher);

		return this;
	}

	public <U> ComposeBuilder<T> withFeature(
			final String featureName,
			final Function<T, U> featureFunction,
			final Object value)
	{
		return withFeature(featureName, featureFunction, equalTo(value));
	}

	public Matcher<T> build()
	{
		final Matcher<T> matcher = ComposeMatchers.compose(compositeDescription, matchers);

		return matcher;
	}

	public static <T> ComposeBuilder<T> compose()
	{
		return new ComposeBuilder<>();
	}

	public static <T> ComposeBuilder<T> compose(final Class<T> class1)
	{
		return new ComposeBuilder<>();
	}

	public static <T> ComposeBuilder<T> of(final Class<T> class1)
	{
		return compose(class1);
	}
}

Example

		return ComposeBuilder.of(WeaponStatus.class)
				.withDescription("a weapon")
				.withFeature("cooldown", WeaponStatus::getCooldown, 5)
				.build();

dtandersen avatar May 21 '21 05:05 dtandersen

Hi @dtandersen, thanks for the submission and sorry for the delay.

I went for static imports rather than a builder pattern as it's more in the style of Hamcrest, but I appreciate the benefits of a fluent style. I'll leave this issue open and see if there's enough demand to add this to the library.

markhobson avatar Jun 10 '21 10:06 markhobson