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

berlin.yuna.hamcrest.matcher.AndWait Maven / Gradle / Ivy

There is a newer version: 1.3.57
Show newest version
package berlin.yuna.hamcrest.matcher;


import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeDiagnosingMatcher;

import java.util.function.Supplier;

public class AndWait extends TypeSafeDiagnosingMatcher> {

    private final Matcher expected;
    private final int timeoutMs;

    @Override
    protected boolean matchesSafely(final Supplier actual, final Description description) {
        T result = null;
        final long finalTime = System.currentTimeMillis() + timeoutMs;
        while (System.currentTimeMillis() < finalTime) {
            result = actual.get();
            if (matchesExpected(result)) return true;
        }

        prepareDescription(description, result);
        return false;
    }

    @Override
    public void describeTo(final Description description) {

    }

    public static  AndWait andWait(final Matcher expected) {
        return new AndWait<>(expected, 15000);
    }

    public static  AndWait andWait(final Matcher expected, final int timeoutMs) {
        return new AndWait<>(expected, timeoutMs);
    }

    public AndWait(final Matcher expected) {
        this(expected, 15000);
    }

    public AndWait(final Matcher expected, final int timeoutMs) {
        this.expected = expected;
        this.timeoutMs = timeoutMs;
    }

    private boolean matchesExpected(final T actual) {
        if (expected.matches(actual)) {
            return true;
        } else {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }

    private void prepareDescription(final Description description, final T result) {
        description
                .appendText("[Timeout]\n")
                .appendText("\nExpected: ")
                .appendDescriptionOf(expected)
                .appendText("\n     but: ");
        expected.describeMismatch(result, description);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy