下面列出了org.mockito.hamcrest.MockitoHamcrest#org.hamcrest.BaseMatcher 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void assertTypeContains(List<Type> expectedTypes, List<Node> nodes) {
final HashSet<Type> types = new HashSet<>();
final EnumerableRelImplementor.TypeFinder typeFinder =
new EnumerableRelImplementor.TypeFinder(types);
for (Node node : nodes) {
node.accept(typeFinder);
}
Assert.assertThat(types, new BaseMatcher<HashSet<Type>>() {
@Override public boolean matches(Object o) {
final Set<Type> actual = (HashSet<Type>) o;
return actual.containsAll(expectedTypes);
}
@Override public void describeTo(Description description) {
description.appendText("Expected a set of types containing all of: ")
.appendText(Objects.toString(expectedTypes));
}
});
}
private Matcher<? super Throwable> errorMatches(Throwable expected) {
return new BaseMatcher<Throwable>() {
@Override public boolean matches(Object item) {
if (!(item instanceof Throwable)) {
return false;
}
Throwable error = (Throwable) item;
return expected != null
&& Objects.equals(error.getClass(), expected.getClass())
&& Objects.equals(error.getMessage(), expected.getMessage());
}
@Override public void describeTo(Description description) {
description.appendText("is ").appendText(expected.toString());
}
};
}
@Nonnull private BaseMatcher<JsonFunctions.JsonPathContext> contextMatches(
JsonFunctions.JsonPathContext expected) {
return new BaseMatcher<JsonFunctions.JsonPathContext>() {
@Override public boolean matches(Object item) {
if (!(item instanceof JsonFunctions.JsonPathContext)) {
return false;
}
JsonFunctions.JsonPathContext context = (JsonFunctions.JsonPathContext) item;
if (Objects.equals(context.mode, expected.mode)
&& Objects.equals(context.obj, expected.obj)) {
if (context.exc == null && expected.exc == null) {
return true;
}
return context.exc != null && expected.exc != null
&& Objects.equals(context.exc.getClass(), expected.exc.getClass())
&& Objects.equals(context.exc.getMessage(), expected.exc.getMessage());
}
return false;
}
@Override public void describeTo(Description description) {
description.appendText("is ").appendText(expected.toString());
}
};
}
@Test
public void testBadIngest() {
thrown.expect(RuntimeException.class);
//should not break at table duplicate check, should fail at model duplicate check
thrown.expectCause(new BaseMatcher<Throwable>() {
@Override
public boolean matches(Object item) {
if (item instanceof IllegalStateException) {
if (((IllegalStateException) item).getMessage().equals("Already exist a model called test_kylin_inner_join_model_desc")) {
return true;
}
}
return false;
}
@Override
public void describeTo(Description description) {
}
});
String srcPath = this.getClass().getResource("/cloned_cube_meta.zip").getPath();
CubeMetaIngester.main(new String[] { "-project", "default", "-srcPath", srcPath });
}
/**
* Create a matcher that wrapps the specified matcher and tests against the
* {@link Throwable#getCause() cause} of an exception. If the item tested
* is {@code null} not a {@link Throwable} the wrapped matcher will be called
* with a {@code null} item.
*
* <p>Often useful when working with JUnit {@link ExpectedException}
* {@link Rule @Rule}s, for example:
* <pre>
* thrown.expect(DataAccessException.class);
* thrown.except(exceptionCause(isA(SQLException.class)));
* </pre>
*
* @param matcher the matcher to wrap (must not be null)
* @return a matcher that tests using the exception cause
*/
@SuppressWarnings("unchecked")
public static <T> Matcher<T> exceptionCause(final Matcher<T> matcher) {
return (Matcher<T>) new BaseMatcher<Object>() {
@Override
public boolean matches(Object item) {
Throwable cause = null;
if (item != null && item instanceof Throwable) {
cause = ((Throwable)item).getCause();
}
return matcher.matches(cause);
}
@Override
public void describeTo(Description description) {
description.appendText("exception cause ").appendDescriptionOf(matcher);
}
};
}
private static Matcher<? super CountingSubscription> matchValueOrCancelled(
Matcher<? super Long> valueMatcher) {
return new BaseMatcher<CountingSubscription>() {
@Override
public void describeTo(final Description description) {
valueMatcher.describeTo(description);
description.appendText(" or not cancelled.");
}
@Override
public boolean matches(final Object o) {
if (!(o instanceof CountingSubscription)) {
return false;
}
CountingSubscription s = (CountingSubscription) o;
return valueMatcher.matches(s.requestedReceived()) || s.isCancelled();
}
};
}
/**
* Returns the first {@link SWTBotLabel} with the given text, or {@code null} if none was found.
*
* @param text
* the label text
* @return the first {@link SWTBotLabel} with the given text, or {@code null} if none was found
*/
public SWTBotLabel getLabel(final String text) {
List<Label> labels = finder.findControls(new BaseMatcher<Label>() {
@Override
public boolean matches(final Object item) {
return item instanceof Label && ((Label) item).getText().equals(text);
}
@Override
public void describeTo(final Description description) {}
});
if (labels.isEmpty()) {
return null;
} else {
return new SWTBotLabel(labels.get(0));
}
}
@Factory
@Deprecated
/**
* Please avoid using as the hamcrest way of reporting error wraps a multi-line
* text into a single line and makes hard to understand the problem.
* Instead, please try to use the spock/groovy assert and {@link #containsLine(String, String)}
*/
public static Matcher<String> containsLine(final String line) {
return new BaseMatcher<String>() {
public boolean matches(Object o) {
return containsLine(equalTo(line)).matches(o);
}
public void describeTo(Description description) {
description.appendText("a String that contains line ").appendValue(line);
}
};
}
@Factory
public static Matcher<Object> isSerializable() {
return new BaseMatcher<Object>() {
public boolean matches(Object o) {
try {
new ObjectOutputStream(new ByteArrayOutputStream()).writeObject(o);
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
public void describeTo(Description description) {
description.appendText("is serializable");
}
};
}
@Factory
@Deprecated
/**
* Please avoid using as the hamcrest way of reporting error wraps a multi-line
* text into a single line and makes hard to understand the problem.
* Instead, please try to use the spock/groovy assert and {@link #containsLine(String, String)}
*/
public static Matcher<String> containsLine(final String line) {
return new BaseMatcher<String>() {
public boolean matches(Object o) {
return containsLine(equalTo(line)).matches(o);
}
public void describeTo(Description description) {
description.appendText("a String that contains line ").appendValue(line);
}
};
}
@Factory
public static Matcher<Object> isSerializable() {
return new BaseMatcher<Object>() {
public boolean matches(Object o) {
try {
new ObjectOutputStream(new ByteArrayOutputStream()).writeObject(o);
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
public void describeTo(Description description) {
description.appendText("is serializable");
}
};
}
public String toString() {
if (invalidMatcherList.isEmpty()) {
String validMatchers =
featureMatcherList.stream()
.map(Pair::getLeft)
.map(BaseMatcher::toString)
.collect(Collectors.joining(","));
return "All matchers suceeded: " + validMatchers;
}
Description description = new StringDescription();
// result.append("A ClientCall with the following properties:");
for (Pair<FeatureMatcher, Object> pair : invalidMatcherList) {
FeatureMatcher invalidMatcher = pair.getLeft();
description.appendText("Expecting '");
invalidMatcher.describeTo(description);
description.appendText("', but got values:").appendValue(pair.getRight());
}
return description.toString();
}
/**
* Matches a view that is a ComponentHost that matches subMatcher.
*
* <p>In Espresso tests, when you need to match a View, we recommend using this matcher and nest
* any of the other matchers in this class along with it. For example <code>
* componentHost(withText("foobar"))</code> or <code>
* componentHost(withContentDescription("foobar"))</code>.
*
* <p>While it's definitely possible to use Espresso's ViewMatchers directly to match
* ComponentHosts, using these methods ensure that we can handle weirdness in the view hierarchy
* that comes from the component stack.
*/
public static Matcher<View> componentHost(final Matcher<? extends ComponentHost> subMatcher) {
return new BaseMatcher<View>() {
@Override
public boolean matches(Object item) {
if (!(item instanceof ComponentHost)) {
return false;
}
return subMatcher.matches((ComponentHost) item);
}
@Override
public void describeTo(Description description) {
description.appendText("Expected to be a ComponentHost matching: ");
subMatcher.describeTo(description);
}
};
}
public static Matcher<ComponentHost> withText(final Matcher<String> textMatcher) {
return new BaseMatcher<ComponentHost>() {
@Override
public boolean matches(Object item) {
if (!(item instanceof ComponentHost)) {
return false;
}
ComponentHost host = (ComponentHost) item;
for (CharSequence foundText : host.getTextContent().getTextItems()) {
if (foundText != null && textMatcher.matches(foundText.toString())) {
return true;
}
}
return false;
}
@Override
public void describeTo(Description description) {
description.appendText("ComponentHost should have text that matches: ");
textMatcher.describeTo(description);
}
};
}
private BaseMatcher<BindException> getMatcher(String message, String field) {
return new BaseMatcher<BindException>() {
@Override
public void describeTo(Description description) {
}
@Override
public boolean matches(Object item) {
BindException ex = (BindException) ((Exception) item).getCause();
ObjectError error = ex.getAllErrors().get(0);
boolean messageMatches = message.equals(error.getDefaultMessage());
if (field == null) {
return messageMatches;
}
String fieldErrors = ((FieldError) error).getField();
return messageMatches && fieldErrors.equals(field);
}
};
}
/**
* Tests if a shell with a specific type of data contained (e.g. Window).
*
* @param bot
* to use
* @param clazz
* class of data contained to check for
*/
@SuppressWarnings("rawtypes")
public static void assertShellWithDataTypeVisible(final SWTWorkbenchBot bot, final Class clazz) {
bot.waitUntil(Conditions.waitForShell(new BaseMatcher<Shell>() {
@SuppressWarnings("unchecked")
public boolean matches(final Object item) {
return UIThreadRunnable.syncExec(new Result<Boolean>() {
public Boolean run() {
if (item instanceof Shell) {
Object shellData = ((Shell) item).getData();
if (shellData != null) {
return clazz.isAssignableFrom(shellData.getClass());
}
}
return false;
}
});
}
public void describeTo(final Description description) {
description.appendText("Shell for " + clazz.getName());
}
}));
}
public static Matcher<Float> floatCloseTo(float value, float range) {
return new BaseMatcher<Float>() {
private Matcher<Double> doubleMatcher = null;
@Override
public boolean matches(Object item) {
if (item instanceof Float) {
return (doubleMatcher = closeTo(value, range)).matches(((Float)item).doubleValue());
}
else {
return (doubleMatcher = closeTo(value, range)).matches(item);
}
}
@Override
public void describeTo(Description description) {
doubleMatcher.describeTo(description);
}
};
}
/**
* Create a matcher that wrapps the specified matcher and tests against the
* {@link Throwable#getCause() cause} of an exception. If the item tested
* is {@code null} not a {@link Throwable} the wrapped matcher will be called
* with a {@code null} item.
*
* <p>Often useful when working with JUnit {@link ExpectedException}
* {@link Rule @Rule}s, for example:
* <pre>
* thrown.expect(DataAccessException.class);
* thrown.except(exceptionCause(isA(SQLException.class)));
* </pre>
*
* @param matcher the matcher to wrap (must not be null)
* @return a matcher that tests using the exception cause
*/
@SuppressWarnings("unchecked")
public static <T> Matcher<T> exceptionCause(final Matcher<T> matcher) {
return (Matcher<T>) new BaseMatcher<Object>() {
@Override
public boolean matches(Object item) {
Throwable cause = null;
if(item != null && item instanceof Throwable) {
cause = ((Throwable)item).getCause();
}
return matcher.matches(cause);
}
@Override
public void describeTo(Description description) {
description.appendText("exception cause ").appendDescriptionOf(matcher);
}
};
}
@Contract(pure = true)
@NotNull
private static Matcher<FlutterWidget> hasCategories(@Nullable String... category) {
final List<String> expected = category != null ? Arrays.asList(category) : Collections.emptyList();
return new BaseMatcher<FlutterWidget>() {
@Override
public boolean matches(final Object item) {
final List<String> categories = ((FlutterWidget)item).getCategories();
return categories != null && categories.containsAll(expected);
}
@Override
public void describeTo(final Description description) {
description.appendText("getCategories should return ").appendValue(category);
}
};
}
@Contract(pure = true)
@NotNull
private static Matcher<FlutterWidget> hasCategories(@Nullable String... category) {
final List<String> expected = category != null ? Arrays.asList(category) : Collections.emptyList();
return new BaseMatcher<FlutterWidget>() {
@Override
public boolean matches(final Object item) {
final List<String> categories = ((FlutterWidget)item).getCategories();
return categories != null && categories.containsAll(expected);
}
@Override
public void describeTo(final Description description) {
description.appendText("getCategories should return ").appendValue(category);
}
};
}
private Matcher<CharacterRule> usesCharacters(final CharacterData characterData) {
return new BaseMatcher<CharacterRule>() {
@Override
public boolean matches(final Object item) {
final CharacterRule rule = (CharacterRule) item;
return rule.getValidCharacters().equals(characterData.getCharacters());
}
@Override
public void describeTo(final Description description) {
description.appendText("getValidCharacters() should equal")
.appendValue(characterData.getCharacters());
}
};
}
private void requestHeaders(ResponseActions expect, RequestPattern request) {
if (request.getHeaders() != null) {
for (final String header : request.getHeaders().keySet()) {
final MultiValuePattern pattern = request.getHeaders().get(header);
expect.andExpect(header(header, new BaseMatcher<String>() {
@Override
public boolean matches(Object item) {
return pattern.match(
new MultiValue(header, Arrays.asList((String) item)))
.isExactMatch();
}
@Override
public void describeTo(Description description) {
description
.appendText("should match header: " + header + " with ")
.appendText(pattern.getExpected());
}
}));
}
}
}
protected Matcher<T> jsonNumber(final Number e) {
return new BaseMatcher<T>() {
@Override
@SuppressWarnings("unchecked")
public boolean matches(final Object n) {
T actual = (T) n;
T expected = runtime().createNumber(e.doubleValue());
return runtime().typeOf(actual) == JmesPathType.NUMBER && runtime().compare(actual, expected) == 0;
}
@Override
public void describeTo(Description description) {
description.appendText("JSON number with value ").appendValue(e);
}
};
}
protected Matcher<T> jsonArrayOfStrings(final String... strs) {
return new BaseMatcher<T>() {
@Override
@SuppressWarnings("unchecked")
public boolean matches(final Object n) {
List<T> input = runtime().toList((T) n);
if (input.size() != strs.length) {
return false;
}
for (int i = 0; i < strs.length; i++) {
if (!runtime().toString(input.get(i)).equals(strs[i])) {
return false;
}
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText("JSON array ").appendValue(strs);
}
};
}
@Test
public void loadBalancerFilterNoClientWorks() {
testClient.get().uri("/get").header("Host", "www.loadbalancerclientempty.org")
.exchange().expectStatus().value(new BaseMatcher<Integer>() {
@Override
public boolean matches(Object item) {
if (Integer.class.isInstance(item)) {
Integer toMatch = (Integer) item;
return toMatch.intValue() == 503;
}
return false;
}
@Override
public void describeTo(Description description) {
description.appendText("Expected 503");
}
});
}
private static <T> Matcher<Collection<T>> containsExactly(final Collection<T> expected) {
return new BaseMatcher<Collection<T>>() {
@Override
public boolean matches(Object o) {
return o != null &&
o instanceof Collection &&
ImmutableSet.copyOf((Collection) o).equals(ImmutableSet.copyOf(expected));
}
@Override
public void describeTo(Description description) {
description.appendText("contains exactly ").appendValue(expected);
}
};
}
private Matcher<ListObjectsRequest> listObjectRequest(final String bucket, final String prefix, @Nullable final String marker) {
return new BaseMatcher<ListObjectsRequest>() {
@Override
public boolean matches(Object item) {
ListObjectsRequest request = (ListObjectsRequest) item;
return request != null &&
request.getBucketName().equals(bucket) &&
request.getPrefix().equals(prefix) &&
Objects.equals(request.getMarker(), marker);
}
@Override
public void describeTo(Description description) {
description.appendText("ListObjectRequest[s3://").appendText(bucket).appendText("/").appendText(prefix);
if (marker != null) {
description.appendText(", marker=").appendText(marker);
}
description.appendText("]");
}
};
}
/**
* Asserts that the specified field alias is parsed as expected.
*
* <p>SQL parser un-escapes the qouted identifiers, for example.
*/
private Matcher<PCollection<Row>> parsedAs(String expected) {
return new BaseMatcher<PCollection<Row>>() {
@Override
public boolean matches(Object actual) {
PCollection<Row> result = (PCollection<Row>) actual;
PAssert.thatSingleton(result).satisfies(assertFieldNameIs(expected));
pipeline.run();
return true;
}
@Override
public void describeTo(Description description) {
description.appendText("field alias matches");
}
};
}
private Request expectPath(String path) {
return argThat(new BaseMatcher<Request>() {
@Override
public void describeTo(Description description) {
description.appendText("Requested URL does not match expected: " + path);
}
@Override
public boolean matches(Object o) {
Request request = (Request) o;
return request.url().encodedPath().equals(path);
}
});
}
public static Matcher<Double> epsilonEqualTo(final double b, final double epsilon) {
return new BaseMatcher<Double>() {
@Override
public boolean matches(Object a) {
return Util.epsilonEquals((Double) a, b, epsilon);
}
@Override
public void describeTo(Description description) {
description.appendText("Should be within +/- ").appendValue(epsilon).appendText(" of ")
.appendValue(b);
}
};
}