Java Code Examples for org.hamcrest.StringDescription

The following examples show how to use org.hamcrest.StringDescription. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: vividus   Source File: DescriptiveSoftAssert.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 2
Source Project: java-hamcrest   Source File: DescriptionUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@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"
          + "}"
  ));
}
 
Example 3
@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;
}
 
Example 4
Source Project: device-automator   Source File: AutomatorAssertion.java    License: MIT License 6 votes vote down vote up
/**
 * 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);
            }
        }
    };
}
 
Example 5
Source Project: ogham   Source File: AssertionHelper.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 6
Source Project: onos   Source File: ImmutableClassChecker.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 7
Source Project: java-hamcrest   Source File: IsPojoTest.java    License: Apache License 2.0 6 votes vote down vote up
@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"
      + "}"
  ));
}
 
Example 8
Source Project: android-test   Source File: ViewAssertions.java    License: Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example 9
Source Project: java-hamcrest   Source File: IsJsonObjectTest.java    License: Apache License 2.0 6 votes vote down vote up
@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"
      + "}"
  ));
}
 
Example 10
Source Project: java-hamcrest   Source File: IsJsonObjectTest.java    License: Apache License 2.0 6 votes vote down vote up
@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"
          + "}"
  ));
}
 
Example 11
@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();
  }
}
 
Example 12
Source Project: java-hamcrest   Source File: IsJsonObjectTest.java    License: Apache License 2.0 6 votes vote down vote up
@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"
          + "}"
  ));
}
 
Example 13
Source Project: flink-spector   Source File: WhileList.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 14
@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();
  }
}
 
Example 15
@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();
  }
}
 
Example 16
@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();
  }
}
 
Example 17
Source Project: java-hamcrest   Source File: IsJsonObject.java    License: Apache License 2.0 6 votes vote down vote up
@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("}");
}
 
Example 18
Source Project: hamcrest-compose   Source File: TestMatchersTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void relaxThenDescribeToDelegates()
{
	StringDescription description = new StringDescription();
	
	relax(is("x")).describeTo(description);
	
	assertThat(description.toString(), is("is \"x\""));
}
 
Example 19
Source Project: android-test   Source File: WebViewAssertions.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 20
Source Project: matchers-java   Source File: TimeoutWaiterTest.java    License: Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example 21
Source Project: hamcrest-junit   Source File: AssumptionTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@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)));
    }
}
 
Example 22
Source Project: hamcrest-compose   Source File: ConjunctionMatcherTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void describeToWhenMatcherDescribesMatcher()
{
	StringDescription description = new StringDescription();
	
	compose("x", anything("y")).describeTo(description);
	
	assertThat(description.toString(), is("x y"));
}
 
Example 23
Source Project: android-test   Source File: ViewInteraction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 24
Source Project: java-hamcrest   Source File: IsJsonNumberTest.java    License: Apache License 2.0 5 votes vote down vote up
@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"
  ));
}
 
Example 25
Source Project: hamcrest-compose   Source File: ConjunctionMatcherTest.java    License: Apache License 2.0 5 votes vote down vote up
@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\""));
}
 
Example 26
@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"));
}
 
Example 27
@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));
}
 
Example 28
Source Project: hamcrest-junit   Source File: AssumptionTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@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)));
    }
}
 
Example 29
Source Project: java-hamcrest   Source File: IsJsonMissingTest.java    License: Apache License 2.0 5 votes vote down vote up
@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"
  ));
}
 
Example 30
Source Project: Lightweight-Stream-API   Source File: StreamMatcherTest.java    License: Apache License 2.0 5 votes vote down vote up
@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"));
}