berlin.yuna.hamcrest.matcher.AndWait Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of and-wait-matcher Show documentation
Show all versions of and-wait-matcher Show documentation
Hamcrest matcher which is waiting (with timeout) for the expected value
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);
}
}