下面列出了android.database.CursorIndexOutOfBoundsException#org.hamcrest.StringDescription 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public <T> boolean assertThat(String businessDescription, String systemDescription, T actual,
Matcher<? super T> matcher)
{
boolean isMatches = matcher.matches(actual);
if (!isMatches)
{
String assertionDescription = getAssertionDescriptionString(actual, matcher);
return recordAssertion(format(businessDescription, assertionDescription),
format(systemDescription, assertionDescription), isMatches);
}
StringDescription description = new StringDescription();
matcher.describeTo(description);
String matchedString = description.toString();
return recordAssertion(businessDescription + StringUtils.SPACE + matchedString,
systemDescription + StringUtils.SPACE + matchedString, isMatches);
}
@Test
public void describeNestMismatchesNoEllipsisBetweenConsecutiveMismatches() throws Exception {
Set<String> allKeys = new LinkedHashSet<>(asList("first", "second", "third", "forth"));
StringDescription description = new StringDescription();
Map<String, Consumer<Description>> mismatchedKeys = ImmutableMap.of(
"second", desc -> desc.appendText("mismatch!"),
"third", desc -> desc.appendText("mismatch!"));
BiConsumer<String, Description> describeKey = (str, desc) -> desc.appendText(str);
DescriptionUtils.describeNestedMismatches(allKeys, description, mismatchedKeys, describeKey);
assertThat(description.toString(), is(
"{\n"
+ " ...\n"
+ " second: mismatch!\n"
+ " third: mismatch!\n"
+ " ...\n"
+ "}"
));
}
@Override
public boolean matches(RestClientCall argument) {
invalidMatcherList.clear();
mismatchDescription = new StringDescription();
for (Pair<FeatureMatcher, Function<RestClientCall, ?>> pair : featureMatcherList) {
FeatureMatcher featureMatcher = pair.getLeft();
featureMatcher.describeMismatch(argument, mismatchDescription);
if (!featureMatcher.matches(argument)) {
Function<RestClientCall, ?> valueExtractor = pair.getRight();
Object apply = argument == null ? null : valueExtractor.apply(argument);
invalidMatcherList.add(Pair.of(featureMatcher, apply));
}
}
boolean isValid = invalidMatcherList.size() == 0;
if (isValid) {
captureArgumentValues(argument);
}
return isValid;
}
/**
* Asserts that the ui element specified in {@link DeviceAutomator#onDevice(UiObjectMatcher)}
* has text that matches the given matcher.
*
* @param matcher The <a href="http://hamcrest.org/JavaHamcrest/">Hamcrest</a> to match against.
* @return
*/
public static AutomatorAssertion text(final Matcher matcher) {
return new AutomatorAssertion() {
@Override
public void wrappedCheck(UiObject object) throws UiObjectNotFoundException {
visible(true).check(object);
if (!matcher.matches(object.getText())) {
StringDescription description = new StringDescription();
description.appendText("Expected ");
matcher.describeTo(description);
description.appendText(" ");
matcher.describeMismatch(object.getText(), description);
assertTrue(description.toString(), false);
}
}
};
}
@SuppressWarnings("unchecked")
private static <T> Description getDescription(String reason, T actual, Matcher<? super T> matcher, String additionalText) {
if (matcher instanceof CustomDescriptionProvider) {
return ((CustomDescriptionProvider<T>) matcher).describe(reason, actual, additionalText);
}
// @formatter:off
Description description = new StringDescription();
description.appendText(getReason(reason, matcher))
.appendText(additionalText==null ? "" : ("\n"+additionalText))
.appendText("\nExpected: ")
.appendDescriptionOf(matcher)
.appendText("\n but: ");
matcher.describeMismatch(actual, description);
// @formatter:on
return description;
}
/**
* Assert that the given class adheres to the immutable class rules, but
* is not declared final. Classes that need to be inherited from cannot be
* declared final.
*
* @param clazz the class to check
*
* @throws java.lang.AssertionError if the class is not an
* immutable class
*/
public static void assertThatClassIsImmutableBaseClass(Class<?> clazz) {
final ImmutableClassChecker checker = new ImmutableClassChecker();
if (!checker.isImmutableClass(clazz, true)) {
final Description toDescription = new StringDescription();
final Description mismatchDescription = new StringDescription();
checker.describeTo(toDescription);
checker.describeMismatch(mismatchDescription);
final String reason =
"\n" +
"Expected: is \"" + toDescription.toString() + "\"\n" +
" but : was \"" + mismatchDescription.toString() + "\"";
throw new AssertionError(reason);
}
}
@Test
public void testMismatchFormattingInOrderOfAddition() throws Exception {
final IsPojo<SomeClass> sut = pojo(SomeClass.class)
.where("foo", is(41))
.where("baz", is(
pojo(SomeClass.class)
.where("foo", is(43))
))
.withProperty("bar", is("not-bar"));
final StringDescription description = new StringDescription();
sut.describeMismatch(new SomeClass(), description);
assertThat(description.toString(), is(
"SomeClass {\n"
+ " foo(): was <42>\n"
+ " baz(): SomeClass {\n"
+ " foo(): was <42>\n"
+ " }\n"
+ " getBar(): was \"bar\"\n"
+ "}"
));
}
@Override
public void check(View view, NoMatchingViewException noViewException) {
StringDescription description = new StringDescription();
description.appendText("'");
viewMatcher.describeTo(description);
if (noViewException != null) {
description.appendText(
String.format(
Locale.ROOT,
"' check could not be performed because view '%s' was not found.\n",
noViewException.getViewMatcherDescription()));
Log.e(TAG, description.toString());
throw noViewException;
} else {
description.appendText("' doesn't match the selected view.");
assertThat(description.toString(), view, viewMatcher);
}
}
@Test
public void testDescription() throws Exception {
final Matcher<JsonNode> sut = jsonObject()
.where("foo", is(jsonInt(1)))
.where("bar", is(jsonBoolean(false)))
.where("baz", is(jsonObject()
.where("foo", is(jsonNull()))));
final StringDescription description = new StringDescription();
sut.describeTo(description);
assertThat(description.toString(), is(
"{\n"
+ " \"foo\": is a number node with value that is <1>\n"
+ " \"bar\": is a boolean node with value that is <false>\n"
+ " \"baz\": is {\n"
+ " \"foo\": is a null node\n"
+ " }\n"
+ "}"
));
}
@Test
public void multipleConsecutiveMismatchesHaveNoEllipsis() throws Exception {
final Matcher<JsonNode> sut = jsonObject()
.where("foo", is(jsonInt(1)))
.where("bar", is(jsonInt(2)))
.where("baz", is(jsonInt(3)));
final ObjectNode nestedMismatches = NF.objectNode()
.put("foo", -1)
.put("bar", "was string")
.put("baz", 3);
final StringDescription description = new StringDescription();
sut.describeMismatch(nestedMismatches, description);
assertThat(description.toString(), is(
"{\n"
+ " \"foo\": was a number node with value that was <-1>\n"
+ " \"bar\": was not a number node, but a string node\n"
+ " ...\n"
+ "}"
));
}
@Test
public void testInterruptedMismatchFormatting() throws Exception {
final SettableFuture<Void> future = SettableFuture.create();
try {
// Interrupt this current thread so that future.get() will throw InterruptedException
Thread.currentThread().interrupt();
final StringDescription description = new StringDescription();
SUT.describeMismatch(future, description);
assertThat(description.toString(), is("a future that was not done"));
} finally {
// Clear the interrupted flag to avoid interference between tests
Thread.interrupted();
}
}
@Test
public void testMismatchNested() throws Exception {
final Matcher<JsonNode> sut = is(
jsonObject()
.where("foo", is(jsonInt(1)))
.where("bar", is(jsonBoolean(true)))
.where("baz", is(
jsonObject()
.where("foo", is(jsonNull())))));
final StringDescription description = new StringDescription();
sut.describeMismatch(NF.objectNode().put("foo", 1).put("bar", true)
.set("baz", NF.objectNode().set("foo", NF.booleanNode(false))),
description);
assertThat(description.toString(), is(
"{\n"
+ " ...\n"
+ " \"baz\": {\n"
+ " \"foo\": was not a null node, but a boolean node\n"
+ " }\n"
+ "}"
));
}
@Override
public boolean matchesSafely(Iterable<T> objects, Description mismatch) {
int numMatches = 0;
int numMismatches = 0;
Description mismatches = new StringDescription();
int i = 0;
for (T item : objects) {
if (!matcher.matches(item)) {
if (numMismatches < 10) {
matcher.describeMismatch(item, mismatches);
mismatches.appendText(" on record #" + (i + 1));
}
numMismatches++;
} else {
numMatches++;
}
if (!validWhile(numMatches, numMismatches)) {
describeMismatch(numMatches, numMismatches, true, mismatch, mismatches);
return false;
}
i++;
}
describeMismatch(numMatches, numMismatches, false, mismatch, mismatches);
return validAfter(numMatches);
}
@Test
public void testInterruptedMismatchFormatting() throws Exception {
final SettableFuture<Void> future = SettableFuture.create();
try {
// Interrupt this current thread so that future.get() will throw InterruptedException
Thread.currentThread().interrupt();
final StringDescription description = new StringDescription();
SUT.describeMismatch(future, description);
assertThat(description.toString(), is("a future that was not completed"));
} finally {
// Clear the interrupted flag to avoid interference between tests
Thread.interrupted();
}
}
@Test
public void testCancelledMismatchFormatting() throws Exception {
final SettableFuture<Void> future = SettableFuture.create();
try {
// Cancel the future
future.cancel(true);
final StringDescription description = new StringDescription();
SUT.describeMismatch(future, description);
assertThat(description.toString(), is("a future that was cancelled"));
} finally {
// Clear the interrupted flag to avoid interference between tests
Thread.interrupted();
}
}
@Test
public void testInterruptedMismatchFormatting() throws Exception {
final CompletableFuture<Void> future = runAsync(waitUntilInterrupted());
try {
// Interrupt this current thread so that future.get() will throw InterruptedException
Thread.currentThread().interrupt();
final StringDescription description = new StringDescription();
SUT.describeMismatch(future, description);
assertThat(description.toString(), is("a stage that was not completed"));
} finally {
// Clear the interrupted flag to avoid interference between tests
Thread.interrupted();
}
}
@Override
public void describeTo(Description description) {
description.appendText("{\n");
for (Map.Entry<String, Matcher<? super JsonNode>> entryMatcher : entryMatchers.entrySet()) {
final String key = entryMatcher.getKey();
final Matcher<? super JsonNode> valueMatcher = entryMatcher.getValue();
description.appendText(" ");
describeKey(key, description);
description.appendText(": ");
final Description innerDescription = new StringDescription();
valueMatcher.describeTo(innerDescription);
DescriptionUtils.indentDescription(description, innerDescription);
}
description.appendText("}");
}
@Test
public void relaxThenDescribeToDelegates()
{
StringDescription description = new StringDescription();
relax(is("x")).describeTo(description);
assertThat(description.toString(), is("is \"x\""));
}
@Override
protected void checkResult(WebView view, E result) {
StringDescription description = new StringDescription();
description.appendText("'");
resultMatcher.describeTo(description);
description.appendText("' doesn't match: ");
description.appendText(null == result ? "null" : resultDescriber.apply(result));
assertThat(description.toString(), result, resultMatcher);
}
@Test
public void shouldReturnMinutesInDescription() throws Exception {
StringDescription description = new StringDescription();
TimeoutWaiter.timeoutHasExpired(TimeUnit.MINUTES.toMillis(2)).describeTo(description);
assertThat("Should format millis as minutes if can", description.toString(), equalTo("2 minutes"));
}
@Test
public void failingAssumeWithMessageReportsBothMessageAndMatcher() {
String message = "Some random message string.";
Matcher<Integer> assumption = equalTo(4);
try {
assumeThat(message, 3, assumption);
} catch (org.junit.AssumptionViolatedException e) {
assertTrue(e.getMessage().contains(message));
assertTrue(e.getMessage().contains(StringDescription.toString(assumption)));
}
}
@Test
public void describeToWhenMatcherDescribesMatcher()
{
StringDescription description = new StringDescription();
compose("x", anything("y")).describeTo(description);
assertThat(description.toString(), is("x y"));
}
/**
* Performs the given action on the view selected by the current view matcher. Should be executed
* on the main thread.
*
* @param viewAction the action to execute.
*/
private void doPerform(final SingleExecutionViewAction viewAction) {
checkNotNull(viewAction);
final Matcher<? extends View> constraints = checkNotNull(viewAction.getConstraints());
uiController.loopMainThreadUntilIdle();
View targetView = viewFinder.getView();
Log.i(
TAG,
String.format(
Locale.ROOT,
"Performing '%s' action on view %s",
viewAction.getDescription(),
viewMatcher));
if (!constraints.matches(targetView)) {
// TODO: update this to describeMismatch once hamcrest 1.4 is available
StringDescription stringDescription =
new StringDescription(
new StringBuilder(
"Action will not be performed because the target view "
+ "does not match one or more of the following constraints:\n"));
constraints.describeTo(stringDescription);
stringDescription
.appendText("\nTarget view: ")
.appendValue(HumanReadables.describe(targetView));
if (viewAction.getInnerViewAction() instanceof ScrollToAction
&& isDescendantOfA(isAssignableFrom(AdapterView.class)).matches(targetView)) {
stringDescription.appendText(
"\nFurther Info: ScrollToAction on a view inside an AdapterView will not work. "
+ "Use Espresso.onData to load the view.");
}
throw new PerformException.Builder()
.withActionDescription(viewAction.getDescription())
.withViewDescription(viewMatcher.toString())
.withCause(new RuntimeException(stringDescription.toString()))
.build();
} else {
viewAction.perform(uiController, targetView);
}
}
@Test
public void testDescriptionForEmptyConstructor() throws Exception {
final Matcher<JsonNode> sut = jsonNumber();
final StringDescription description = new StringDescription();
sut.describeTo(description);
assertThat(description.toString(), is(
"a number node with value that is ANYTHING"
));
}
@Test
public void describeMismatchWhenSecondMatcherDoesNotMatchDescribesMismatch()
{
ConjunctionMatcher<Object> matcher = compose(anything()).and(nothing("x"));
StringDescription description = new StringDescription();
matcher.describeMismatch("y", description);
assertThat(description.toString(), is("x was \"y\""));
}
@Test
public void testHasElements() {
assertThat(IntStream.of(1, 2), hasElements());
assertThat(IntStream.empty(), not(hasElements()));
StringDescription description = new StringDescription();
hasElements().describeTo(description);
assertThat(description.toString(), is("a non-empty stream"));
}
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
StringDescription description = new StringDescription();
RecyclerView recyclerView = (RecyclerView) view;
sortedList = withAdapter.itemsToSort(recyclerView);
checkIsNotEmpty(view, description);
description.appendText("The list " + sortedList + " is not sorted");
assertTrue(description.toString(), Ordering.natural().<T>isOrdered(sortedList));
}
@Test
public void failingAssumeThrowsPublicAssumptionViolatedException() {
Matcher<Integer> assumption = equalTo(4);
try {
assumeThat(3, assumption);
} catch (org.junit.AssumptionViolatedException e) {
assertTrue(e.getMessage().contains(StringDescription.toString(assumption)));
}
}
@Test
public void testDescription() throws Exception {
final Matcher<JsonNode> sut = jsonMissing();
final StringDescription description = new StringDescription();
sut.describeTo(description);
assertThat(description.toString(), is(
"a missing node"
));
}
@Test
public void testHasElements() {
assertThat(Stream.of(1, 2), hasElements());
assertThat(Stream.empty(), not(hasElements()));
StringDescription description = new StringDescription();
hasElements().describeTo(description);
assertThat(description.toString(), is("a non-empty stream"));
}