Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add compose matcher builder #20

Open
dtandersen opened this issue May 21, 2021 · 1 comment
Open

Add compose matcher builder #20

dtandersen opened this issue May 21, 2021 · 1 comment

Comments

@dtandersen
Copy link

dtandersen commented May 21, 2021

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();
@markhobson
Copy link
Owner

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 markhobson changed the title Are you interested in this? Add compose matcher builder Jun 10, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants