Java 类junit.framework.AssertionFailedError 实例源码

项目:googles-monorepo-demo    文件:AbstractIteratorTester.java   
private void compareResultsForThisListOfStimuli() {
  int removes = Collections.frequency(Arrays.asList(stimuli), remove);
  if ((!features.contains(IteratorFeature.SUPPORTS_REMOVE) && removes > 1)
      || (stimuli.length >= 5 && removes > 2)) {
    // removes are the most expensive thing to test, since they often throw exceptions with stack
    // traces, so we test them a bit less aggressively
    return;
  }

  MultiExceptionListIterator reference = new MultiExceptionListIterator(expectedElements);
  I target = newTargetIterator();
  for (int i = 0; i < stimuli.length; i++) {
    try {
      stimuli[i].executeAndCompare(reference, target);
      verify(reference.getElements());
    } catch (AssertionFailedError cause) {
      Helpers.fail(cause, "failed with stimuli " + subListCopy(stimuli, i + 1));
    }
  }
}
项目:lams    文件:JUnitServlet.java   
private void displayProblems( PrintWriter writer, String kind, int count, Enumeration enumeration ) {
    if (count != 0) {
        displayProblemTitle( writer, getFormatted( count, kind ) );
        Enumeration e = enumeration;
        for (int i = 1; e.hasMoreElements(); i++) {
            TestFailure failure = (TestFailure) e.nextElement();
            displayProblemDetailHeader( writer, i, failure.failedTest().toString() );
            if (failure.thrownException() instanceof AssertionFailedError) {
                displayProblemDetail( writer, failure.thrownException().getMessage() );
            } else {
                displayProblemDetail( writer, BaseTestRunner.getFilteredTrace( failure.thrownException() ) );
            }
            displayProblemDetailFooter( writer );
        }
    }
}
项目:jetedge    文件:FieldAttributesTest.java   
@Test
public void testFieldSetterWithArray() {
    FieldAttributes fieldAttributes =
            ClassAttributes.create(Person.class)
                    .getFields().stream()
                    .filter(f -> "secretName".equals(f.getName()))
                    .findFirst().orElseThrow(AssertionFailedError::new);
    BiConsumer setter = fieldAttributes.getSetter();
    Person instance = new Person();
    Character[] secretName = {'s', 'u', 'p', 'e', 'r', 'm', 'a', 'n'};

    setter.accept(instance, secretName);
    char[] fromInstance = instance.getSecretName();
    for (int i = 0; i < secretName.length; i++) {
        assertTrue(secretName[i].equals(fromInstance[i]));
    }
}
项目:incubator-netbeans    文件:MockPropertyChangeListener.java   
/**
 * Expects a single event to be fired.
 * After this call, the list of received events is reset, so each call checks events since the last call.
 * @param propertyName optional property name which is expected (or null for any)
 * @param timeout a timeout in milliseconds (zero means no timeout)
 */
public synchronized void expectEvent(String expectedPropertyName, long timeout) throws AssertionFailedError {
    try {
        if (events.isEmpty()) {
            try {
                wait(timeout);
            } catch (InterruptedException x) {
                fail(compose("Timed out waiting for event"));
            }
        }
        assertFalse(compose("Did not get event"), events.isEmpty());
        assertFalse(compose("Got too many events"), events.size() > 1);
        PropertyChangeEvent received = events.iterator().next();
        if (expectedPropertyName != null) {
            assertEquals(msg, expectedPropertyName, received.getPropertyName());
        }
    } finally {
        reset();
    }
}
项目:guava-mock    文件:EquivalenceTesterTest.java   
public void testTest_hash() {
  Object group1Item1 = new TestObject(1, 1);
  Object group1Item2 = new TestObject(1, 2);

  equivalenceMock.expectEquivalent(group1Item1, group1Item2);
  equivalenceMock.expectEquivalent(group1Item2, group1Item1);

  equivalenceMock.expectHash(group1Item1, 1);
  equivalenceMock.expectHash(group1Item2, 2);

  equivalenceMock.replay();

  try {
    tester.addEquivalenceGroup(group1Item1, group1Item2).test();
  } catch (AssertionFailedError expected) {
    String expectedMessage =
        "the hash (1) of TestObject{group=1, item=1} [group 1, item 1] must be "
        + "equal to the hash (2) of TestObject{group=1, item=2} [group 1, item 2]";
    if (!expected.getMessage().contains(expectedMessage)) {
      fail("<" + expected.getMessage() + "> expected to contain <" + expectedMessage + ">");
    }
    return;
  }
  fail();
}
项目:incubator-netbeans    文件:CssTestBase.java   
protected void assertAlternatives(ResolvedProperty propertyValue, String... expected) {
    Set<ValueGrammarElement> alternatives = propertyValue.getAlternatives();
    Collection<String> alts = convert(alternatives);
    Collection<String> expc = new ArrayList<String>(Arrays.asList(expected));
    if (alts.size() > expc.size()) {
        alts.removeAll(expc);
        throw new AssertionFailedError(String.format("Found %s unexpected alternative(s): %s", alts.size(), toString(alts)));
    } else if (alts.size() < expc.size()) {
        expc.removeAll(alts);
        throw new AssertionFailedError(String.format("There're %s expected alternative(s) missing : %s", expc.size(), toString(expc)));
    } else {
        Collection<String> alts2 = new ArrayList<String>(alts);
        Collection<String> expc2 = new ArrayList<String>(expc);

        alts2.removeAll(expc);
        expc2.removeAll(alts);

        assertTrue(String.format("Missing expected: %s; Unexpected: %s", toString(expc2), toString(alts2)), alts2.isEmpty() && expc2.isEmpty());

    }
}
项目:s-store    文件:VoltJUnitFormatter.java   
@Override
public void addFailure(Test arg0, AssertionFailedError arg1) {
    String testName = arg0.toString();
    testName = testName.substring(0, testName.indexOf('('));

    out.println("    " + testName + " failed an assertion.");
    StackTraceElement[] st = arg1.getStackTrace();
    int i = 0;
    for (StackTraceElement ste : st) {
        if (ste.getClassName().contains("org.voltdb") == false)
            continue;
        out.printf("        %s(%s:%d)\n", ste.getClassName(), ste.getFileName(), ste.getLineNumber());
        if (++i == 3) break;
    }
    m_failures++;
}
项目:guava-mock    文件:EqualsTesterTest.java   
/**
 * Test for an invalid hashCode method, i.e., one that returns different
 * value for objects that are equal according to the equals method
 */
public void testInvalidHashCode() {
  Object a = new InvalidHashCodeObject(1, 2);
  Object b = new InvalidHashCodeObject(1, 2);
  equalsTester.addEqualityGroup(a, b);
  try {
    equalsTester.testEquals();
  } catch (AssertionFailedError e) {
    assertErrorMessage(
        e, "the Object#hashCode (" + a.hashCode() + ") of " + a
        + " [group 1, item 1] must be equal to the Object#hashCode ("
        + b.hashCode() + ") of " + b);
    return;
  }
  fail("Should get invalid hashCode error");
}
项目:PeSanKita-android    文件:Rfc5724UriTest.java   
@Test public void testInvalidPath() throws Exception {
  final String[] invalidSchemaUris = {
      "",
      ":",
      "sms:",
      ":sms",
      "sms:?goto=fail",
      "sms:?goto=fail&fail=goto"
  };

  for (String uri : invalidSchemaUris) {
    try {
      new Rfc5724Uri(uri);
      throw new AssertionFailedError("URISyntaxException should be thrown");
    } catch (URISyntaxException e) {
      // success
    }
  }
}
项目:monarch    文件:CacheSerializableRunnable.java   
/**
 * Invokes the {@link #run} method.  If AssertionFailedError is thrown,
 * and repeatTimeoutMs is >0, then repeat the {@link #run} method until
 * it either succeeds or repeatTimeoutMs milliseconds have passed.  The
 * AssertionFailedError is only thrown to the caller if the last run
 * still throws it.
 */
public final void runRepeatingIfNecessary(long repeatTimeoutMs) {
  long start = System.currentTimeMillis();
  AssertionFailedError lastErr = null;
  do {
    try {
      lastErr = null;
      this.run();
      CacheFactory.getAnyInstance().getLogger().fine("Completed " + this);
    } catch (AssertionFailedError err) {
      CacheFactory.getAnyInstance().getLogger().fine("Repeating " + this);
      lastErr = err;
      try {
        Thread.sleep(50);
      } catch (InterruptedException ex) {
        throw new TestException("interrupted", ex);
      }
    }
  } while (lastErr != null && System.currentTimeMillis() - start < repeatTimeoutMs);
  if (lastErr != null) throw lastErr;
}
项目:fuck_zookeeper    文件:ZxidRolloverTest.java   
private void shutdown(int idx) throws Exception {
    qu.shutdown(idx);

    // leader will shutdown, remaining followers will elect a new leader
    PeerStruct peer = qu.getPeer(idx);
    Assert.assertTrue("Waiting for server down", ClientBase.waitForServerDown(
            "127.0.0.1:" + peer.clientPort, ClientBase.CONNECTION_TIMEOUT));

    // if idx is the the leader then everyone will get disconnected,
    // otherwise if idx is a follower then just that client will get
    // disconnected
    if (idx == idxLeader) {
        checkClientDisconnected(idx);
        try {
            checkClientsDisconnected();
        } catch (AssertionFailedError e) {
            // the clients may or may not have already reconnected
            // to the recovered cluster, force a check, but ignore
        }
    } else {
        checkClientDisconnected(idx);
    }
}
项目:jsonverifier    文件:JsonContentVerifier.java   
/**
 * compare JSON to the content of the specified file
 *
 * @param actualJson        JSON to compare
 * @param expectedFileName  file name from which to load expected content
 * @throws IOException          if an I/O error occurs
 * @throws NullPointerException if the file doesn't exist
 */
public void assertJson(String actualJson, String expectedFileName) throws IOException {
    String path = String.format(PATH, testClass.getSimpleName(), methodName, expectedFileName);
    try (InputStream resourceAsStream = testClass.getClassLoader().getResourceAsStream(path)) {
        String expectedJson = IOUtils.toString(resourceAsStream, Charset.defaultCharset());
        JsonNode actual = objectMapper.readTree(actualJson);
        JsonNode expected = objectMapper.readTree(expectedJson);

        LOGGER.info("EXPECTED JSON: " + expectedJson);
        LOGGER.info("ACTUAL JSON: " + actualJson);

        String diff = JsonDiff.asJson(actual, expected).toString();
        if (!diff.equals("[]")) {
            throw new AssertionFailedError("Json objects are not equal: " + diff);
        }
    }
}
项目:googles-monorepo-demo    文件:MapMergeTester.java   
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testMappedToNull() {
  initMapWithNullValue();
  assertEquals(
      "Map.merge(keyMappedToNull, value, function) should return value",
      v3(),
      getMap()
          .merge(
              getKeyForNullValue(),
              v3(),
              (oldV, newV) -> {
                throw new AssertionFailedError(
                    "Should not call merge function if key was mapped to null");
              }));
  expectReplacement(entry(getKeyForNullValue(), v3()));
}
项目:hadoop-oss    文件:TestFsShell.java   
@Test
public void testConfWithInvalidFile() throws Throwable {
  String[] args = new String[1];
  args[0] = "--conf=invalidFile";
  Throwable th = null;
  try {
    FsShell.main(args);
  } catch (Exception e) {
    th = e;
  }

  if (!(th instanceof RuntimeException)) {
    throw new AssertionFailedError("Expected Runtime exception, got: " + th)
        .initCause(th);
  }
}
项目:guava-mock    文件:FuturesTest.java   
public void testTransformAsync_interruptPropagatesToInput() throws Exception {
  SettableFuture<Foo> input = SettableFuture.create();
  AsyncFunction<Foo, Bar> function = new AsyncFunction<Foo, Bar>() {
    @Override
    public ListenableFuture<Bar> apply(Foo unused) {
      throw new AssertionFailedError("Unexpeted call to apply.");
    }
  };
  assertTrue(transformAsync(input, function, directExecutor()).cancel(true));
  assertTrue(input.isCancelled());
  assertTrue(input.wasInterrupted());
}
项目:guava-mock    文件:JSR166TestCase.java   
/**
 * Just like assertNull(x), but additionally recording (using
 * threadRecordFailure) any AssertionFailedError thrown, so that
 * the current testcase will fail.
 */
public void threadAssertNull(Object x) {
    try {
        assertNull(x);
    } catch (AssertionFailedError t) {
        threadRecordFailure(t);
        throw t;
    }
}
项目:bootstrap    文件:TAbstractSequentialSeleniumTest.java   
/**
 * Run sequentially (one instance) the given runnable instance with an error.
 */
@Test(expected = AssertionFailedError.class)
public void testSequentialError() {
    testName = Mockito.mock(TestName.class);
    Mockito.when(testName.getMethodName()).thenReturn("mockTestError");
    mockDriver = Mockito.mock(WebDriver.class);
    Mockito.when(mockDriver.manage()).thenThrow(new AssertionFailedError());
    super.runSequential();
}
项目:GitHub    文件:RealmTests.java   
@Test
public void close_differentThread() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final AssertionFailedError threadAssertionError[] = new AssertionFailedError[1];

    final Thread thatThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                realm.close();
                threadAssertionError[0] = new AssertionFailedError(
                        "Close realm in a different thread should throw IllegalStateException.");
            } catch (IllegalStateException ignored) {
            }
            latch.countDown();
        }
    });
    thatThread.start();

    // Timeout should never happen.
    TestHelper.awaitOrFail(latch);
    if (threadAssertionError[0] != null) {
        throw threadAssertionError[0];
    }
    // After exception thrown in another thread, nothing should be changed to the realm in this thread.
    realm.checkIfValid();
    realm.close();
    realm = null;
}
项目:GitHub    文件:RealmTests.java   
@Test
public void isClosed_differentThread() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final AssertionFailedError threadAssertionError[] = new AssertionFailedError[1];

    final Thread thatThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                realm.isClosed();
                threadAssertionError[0] = new AssertionFailedError(
                        "Call isClosed() of Realm instance in a different thread should throw IllegalStateException.");
            } catch (IllegalStateException ignored) {
            }
            latch.countDown();
        }
    });
    thatThread.start();

    // Timeout should never happen.
    TestHelper.awaitOrFail(latch);
    if (threadAssertionError[0] != null) {
        throw threadAssertionError[0];
    }
    // After exception thrown in another thread, nothing should be changed to the realm in this thread.
    realm.checkIfValid();
    assertFalse(realm.isClosed());
    realm.close();
}
项目:guava-mock    文件:JSR166TestCase.java   
/**
 * Records the given exception using {@link #threadRecordFailure},
 * then rethrows the exception, wrapping it in an
 * AssertionFailedError if necessary.
 */
public void threadUnexpectedException(Throwable t) {
    threadRecordFailure(t);
    t.printStackTrace();
    if (t instanceof RuntimeException)
        throw (RuntimeException) t;
    else if (t instanceof Error)
        throw (Error) t;
    else {
        AssertionFailedError afe =
            new AssertionFailedError("unexpected exception: " + t);
        afe.initCause(t);
        throw afe;
    }
}
项目:guava-mock    文件:NullPointerTesterTest.java   
public void verifyBarPass(Method method, TwoArg bar) {
  try {
    new NullPointerTester().testMethod(bar, method);
  } catch (AssertionFailedError incorrectError) {
    String errorMessage = rootLocaleFormat(
        "Should not have flagged method %s for %s", method.getName(), bar);
    assertNull(errorMessage, incorrectError);
  }
}
项目:googles-monorepo-demo    文件:NullPointerTesterTest.java   
void check() {
  try {
    runTester();
  } catch (AssertionFailedError expected) {
    return;
  }
  fail("Should have failed because enum has no constant");
}
项目:incubator-netbeans    文件:OffsetsBagTest.java   
private void assertMarks(String message, OffsetsBag expected, OffsetsBag actual) {
    try {
        OffsetGapList<OffsetsBag.Mark> expectedMarks = expected.getMarks();
        OffsetGapList<OffsetsBag.Mark> actualMarks = actual.getMarks();
        assertEquals("Different number of marks", expectedMarks.size(), actualMarks.size());
        for(int i = 0; i < expectedMarks.size(); i++) {
            OffsetsBag.Mark expectedMark = expectedMarks.get(i);
            OffsetsBag.Mark actualMark = actualMarks.get(i);
            assertEquals("Different offset at the " + i + "-th mark", expectedMark.getOffset(), actualMark.getOffset());
            assertSame("Different attributes at the " + i + "-th mark", expectedMark.getAttributes(), actualMark.getAttributes());
        }
    } catch (AssertionFailedError afe) {
        StringBuilder sb = new StringBuilder();
        sb.append(message);
        sb.append('\n');
        sb.append("Expected marks (size=");
        sb.append(expected.getMarks().size());
        sb.append("):\n");
        dumpMarks(expected, sb);
        sb.append('\n');
        sb.append("Actual marks (size=");
        sb.append(actual.getMarks().size());
        sb.append("):\n");
        dumpMarks(actual, sb);
        sb.append('\n');

        AssertionFailedError afe2 = new AssertionFailedError(sb.toString());
        afe2.initCause(afe);
        throw afe2;
    }
}
项目:guava-mock    文件:AbstractSequentialIteratorTest.java   
private static <T> Iterator<T> newEmpty() {
  return new AbstractSequentialIterator<T>(null) {
    @Override
    protected T computeNext(T previous) {
      throw new AssertionFailedError();
    }
  };
}
项目:incubator-netbeans    文件:PositionsBagTest.java   
private void assertMarks(String message, PositionsBag expected, PositionsBag actual) {
    try {
        GapList<Position> expectedPositions = expected.getMarks();
        GapList<Position> actualPositions = actual.getMarks();
        GapList<AttributeSet> expectedAttributes = expected.getAttributes();
        GapList<AttributeSet> actualAttributes = actual.getAttributes();
        assertEquals("Different number of marks", expectedPositions.size(), actualPositions.size());
        for(int i = 0; i < expectedPositions.size(); i++) {
            Position expectedPos = expectedPositions.get(i);
            Position actualPos = actualPositions.get(i);
            assertEquals("Different offset at the " + i + "-th mark", expectedPos.getOffset(), actualPos.getOffset());

            AttributeSet expectedAttrib = expectedAttributes.get(i);
            AttributeSet actualAttrib = actualAttributes.get(i);
            assertSame("Different attributes at the " + i + "-th mark", expectedAttrib, actualAttrib);
        }
    } catch (AssertionFailedError afe) {
        StringBuilder sb = new StringBuilder();
        sb.append(message);
        sb.append('\n');
        sb.append("Expected marks (size=");
        sb.append(expected.getMarks().size());
        sb.append("):\n");
        dumpMarks(expected, sb);
        sb.append('\n');
        sb.append("Actual marks (size=");
        sb.append(actual.getMarks().size());
        sb.append("):\n");
        dumpMarks(actual, sb);
        sb.append('\n');

        AssertionFailedError afe2 = new AssertionFailedError(sb.toString());
        afe2.initCause(afe);
        throw afe2;
    }
}
项目:googles-monorepo-demo    文件:NullPointerTesterTest.java   
private static void shouldFail(Class<?> cls, Visibility visibility) {
  try {
    new NullPointerTester().testStaticMethods(cls, visibility);
  } catch (AssertionFailedError expected) {
    return;
  }
  fail("Should detect problem in " + cls.getSimpleName());
}
项目:googles-monorepo-demo    文件:TestPlatform.java   
/**
 * Retrieves the result of a {@code Future} known to be done but uses the {@code get(long,
 * TimeUnit)} overload in order to test that method.
 */
static <V> V getDoneFromTimeoutOverload(Future<V> future) throws ExecutionException {
  checkState(future.isDone(), "Future was expected to be done: %s", future);
  try {
    return getUninterruptibly(future, 0, SECONDS);
  } catch (TimeoutException e) {
    AssertionFailedError error = new AssertionFailedError(e.getMessage());
    error.initCause(e);
    throw error;
  }
}
项目:guava-mock    文件:EqualsTesterTest.java   
/**
 * Test proper handling of case where an object is not equal to itself
 */
public void testNonreflexiveEquals() {
  Object obj = new NonReflexiveObject();
  equalsTester.addEqualityGroup(obj);
  try {
    equalsTester.testEquals();
  } catch (AssertionFailedError e) {
    assertErrorMessage(
        e, obj + " must be Object#equals to itself");
    return;
  }
  fail("Should get non-reflexive error");
}
项目:incubator-netbeans    文件:MockChangeListener.java   
/**
 * Asserts that no change events have been fired.
 */
public synchronized void assertNoEvents() throws AssertionFailedError {
    try {
        assertTrue(msg, events.isEmpty());
    } finally {
        reset();
    }
}
项目:openjdk-jdk10    文件:JSR166TestCase.java   
/**
 * Just like assertEquals(x, y), but additionally recording (using
 * threadRecordFailure) any AssertionFailedError thrown, so that
 * the current testcase will fail.
 */
public void threadAssertEquals(long x, long y) {
    try {
        assertEquals(x, y);
    } catch (AssertionFailedError t) {
        threadRecordFailure(t);
        throw t;
    }
}
项目:guava-mock    文件:IteratorsTest.java   
public void testFilterNothing() {
  Iterator<String> unfiltered = Collections.<String>emptyList().iterator();
  Iterator<String> filtered = Iterators.filter(unfiltered,
      new Predicate<String>() {
        @Override
        public boolean apply(String s) {
          throw new AssertionFailedError("Should never be evaluated");
        }
      });

  List<String> expected = Collections.emptyList();
  List<String> actual = Lists.newArrayList(filtered);
  assertEquals(expected, actual);
}
项目:googles-monorepo-demo    文件:SerializableTesterTest.java   
public void testClassWhichDoesNotImplementEquals() {
  ClassWhichDoesNotImplementEquals orig =
      new ClassWhichDoesNotImplementEquals();
  boolean errorNotThrown = false;
  try {
    SerializableTester.reserializeAndAssert(orig);
    errorNotThrown = true;
  } catch (AssertionFailedError error) {
    // expected
    assertContains("must be Object#equals to", error.getMessage());
  }
  assertFalse(errorNotThrown);
}
项目:googles-monorepo-demo    文件:JSR166TestCase.java   
/**
 * Just like assertTrue(b), but additionally recording (using
 * threadRecordFailure) any AssertionFailedError thrown, so that
 * the current testcase will fail.
 */
public void threadAssertTrue(boolean b) {
    try {
        assertTrue(b);
    } catch (AssertionFailedError t) {
        threadRecordFailure(t);
        throw t;
    }
}
项目:PeSanKita-android    文件:SmsListenerTest.java   
@Test
public void testChallenges() throws Exception {
  for (Entry<String,String> challenge : CHALLENGES.entrySet()) {
    if (!listener.isChallenge(context, challenge.getKey())) {
      throw new AssertionFailedError("SmsListener didn't recognize body as a challenge.");
    }
    assertEquals(listener.parseChallenge(challenge.getKey()), challenge.getValue());
  }
}
项目:googles-monorepo-demo    文件:AbstractPackageSanityTests.java   
private static AssertionFailedError sanityError(
    Class<?> cls, List<String> explicitTestNames, String description, Throwable e) {
  String message = String.format(Locale.ROOT,
      "Error in automated %s of %s\n"
          + "If the class is better tested explicitly, you can add %s() to %sTest",
      description, cls, explicitTestNames.get(0), cls.getName());
  AssertionFailedError error = new AssertionFailedError(message);
  error.initCause(e);
  return error;
}
项目:hadoop    文件:TestNetUtils.java   
private void assertInException(Exception e, String text) throws Throwable {
  String message = extractExceptionMessage(e);
  if (!(message.contains(text))) {
    throw new AssertionFailedError("Wrong text in message "
                                       + "\"" + message + "\""
                                       + " expected \"" + text + "\"")
        .initCause(e);
  }
}
项目:parabuild-ci    文件:TestViewAsterisks.java   
/**
 *  creates a view with a given name and statement, ensures that it's statement is translated as expected, and ensures
 *  that the content of the view is as expected
 *
 *  @param viewName
 *      the name of the to-be-created view
 *  @param columnNames
 *      the names of the columns of the view, as to be specified in the CREATE VIEW statement. Might be null,
 *      in this case the view will be created without an explicit column list
 *  @param viewStatement
 *      the statement of the to-be-created view
 *  @param expectedTranslatedStatement
 *      the expected statement of the view, after it has been implicitly translated by HSQL. If the actual
 *      statement after creation does not match this expected statement, this is a failure condition which
 *      results in a AssertionFailedError being thrown.
 *  @param expectedContent
 *      the expected content of the view. If this is <code>null</code>, it is ignored. Else, if it is a
 *      string, it is interpreted as name of the table which must have the same content as a view. If
 *      it's no string either, it must be a two-dimensional Object array specifying the expected content.
 */
private void checkViewTranslationAndContent(String viewName,
        String[] columnList, String viewStatement,
        String expectedTranslatedStatement,
        Object expectedContent) throws SQLException {

    createView(viewName, columnList, viewStatement);

    String actualTranslatedStatement = getViewStatement(viewName);

    if (!actualTranslatedStatement.equals(expectedTranslatedStatement)) {
        StringBuffer message = new StringBuffer();

        message.append(viewName).append(
            "'s statement not translated as expected\n");
        message.append("original statement:\n  ").append(
            viewStatement).append('\n');
        message.append("expected translated statement:\n  ").append(
            expectedTranslatedStatement).append('\n');
        message.append("actual translated statement:\n  ").append(
            actualTranslatedStatement).append('\n');

        throw new AssertionFailedError(message.toString());
    }

    if (expectedContent != null) {
        if (expectedContent.getClass().equals(String.class)) {
            ensureEqualContent(viewName, (String) expectedContent);
        } else {
            ensureTableContent(viewName, (Object[][]) expectedContent);
        }
    }
}
项目:guava-mock    文件:SerializableTesterTest.java   
public void testClassWhichIsAlwaysEqualButHasDifferentHashcodes() {
  ClassWhichIsAlwaysEqualButHasDifferentHashcodes orig =
      new ClassWhichIsAlwaysEqualButHasDifferentHashcodes();
  boolean errorNotThrown = false;
  try {
    SerializableTester.reserializeAndAssert(orig);
    errorNotThrown = true;
  } catch (AssertionFailedError error) {
    // expected
    assertContains("must be equal to the Object#hashCode", error.getMessage());
  }
  assertFalse(errorNotThrown);
}
项目:guava-mock    文件:EqualsTesterTest.java   
public void testUnequalObjectsInEqualityGroup() {
  EqualsTester tester = new EqualsTester()
      .addEqualityGroup(named("foo"), named("bar"));
  try {
    tester.testEquals();
  } catch (AssertionFailedError e) {
    assertErrorMessage(
        e,
        "foo [group 1, item 1] must be Object#equals to bar [group 1, item 2]");
    return;
  }
  fail("should failed because of unequal objects in the same equality group");
}
项目:googles-monorepo-demo    文件:ClassSanityTesterTest.java   
public void testBadNulls() throws Exception {
  try {
    tester.testNulls(BadNulls.class);
  } catch (AssertionFailedError expected) {
    return;
  }
  fail("should have failed");
}