Java Code Examples for junit.framework.AssertionFailedError

The following are top voted examples for showing how to use junit.framework.AssertionFailedError. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: googles-monorepo-demo   File: AbstractIteratorTester.java   View source code 7 votes vote down vote up
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));
    }
  }
}
 
Example 2
Project: lams   File: JUnitServlet.java   View source code 6 votes vote down vote up
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 );
        }
    }
}
 
Example 3
Project: jetedge   File: FieldAttributesTest.java   View source code 6 votes vote down vote up
@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]));
    }
}
 
Example 4
Project: incubator-netbeans   File: MockPropertyChangeListener.java   View source code 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 5
Project: guava-mock   File: EquivalenceTesterTest.java   View source code 6 votes vote down vote up
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();
}
 
Example 6
Project: incubator-netbeans   File: CssTestBase.java   View source code 6 votes vote down vote up
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());

    }
}
 
Example 7
Project: s-store   File: VoltJUnitFormatter.java   View source code 6 votes vote down vote up
@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++;
}
 
Example 8
Project: guava-mock   File: EqualsTesterTest.java   View source code 6 votes vote down vote up
/**
 * 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");
}
 
Example 9
Project: PeSanKita-android   File: Rfc5724UriTest.java   View source code 6 votes vote down vote up
@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
    }
  }
}
 
Example 10
Project: monarch   File: CacheSerializableRunnable.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 11
Project: fuck_zookeeper   File: ZxidRolloverTest.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 12
Project: jsonverifier   File: JsonContentVerifier.java   View source code 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 13
Project: googles-monorepo-demo   File: MapMergeTester.java   View source code 6 votes vote down vote up
@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()));
}
 
Example 14
Project: hadoop-oss   File: TestFsShell.java   View source code 6 votes vote down vote up
@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);
  }
}
 
Example 15
Project: guava-mock   File: FuturesTest.java   View source code 5 votes vote down vote up
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());
}
 
Example 16
Project: guava-mock   File: JSR166TestCase.java   View source code 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example 17
Project: bootstrap   File: TAbstractSequentialSeleniumTest.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 18
Project: GitHub   File: RealmTests.java   View source code 5 votes vote down vote up
@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;
}
 
Example 19
Project: GitHub   File: RealmTests.java   View source code 5 votes vote down vote up
@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();
}
 
Example 20
Project: guava-mock   File: JSR166TestCase.java   View source code 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example 21
Project: guava-mock   File: NullPointerTesterTest.java   View source code 5 votes vote down vote up
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);
  }
}
 
Example 22
Project: googles-monorepo-demo   File: NullPointerTesterTest.java   View source code 5 votes vote down vote up
void check() {
  try {
    runTester();
  } catch (AssertionFailedError expected) {
    return;
  }
  fail("Should have failed because enum has no constant");
}
 
Example 23
Project: incubator-netbeans   File: OffsetsBagTest.java   View source code 5 votes vote down vote up
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;
    }
}
 
Example 24
Project: guava-mock   File: AbstractSequentialIteratorTest.java   View source code 5 votes vote down vote up
private static <T> Iterator<T> newEmpty() {
  return new AbstractSequentialIterator<T>(null) {
    @Override
    protected T computeNext(T previous) {
      throw new AssertionFailedError();
    }
  };
}
 
Example 25
Project: incubator-netbeans   File: PositionsBagTest.java   View source code 5 votes vote down vote up
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;
    }
}
 
Example 26
Project: googles-monorepo-demo   File: NullPointerTesterTest.java   View source code 5 votes vote down vote up
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());
}
 
Example 27
Project: googles-monorepo-demo   File: TestPlatform.java   View source code 5 votes vote down vote up
/**
 * 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;
  }
}
 
Example 28
Project: guava-mock   File: EqualsTesterTest.java   View source code 5 votes vote down vote up
/**
 * 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");
}
 
Example 29
Project: incubator-netbeans   File: MockChangeListener.java   View source code 5 votes vote down vote up
/**
 * Asserts that no change events have been fired.
 */
public synchronized void assertNoEvents() throws AssertionFailedError {
    try {
        assertTrue(msg, events.isEmpty());
    } finally {
        reset();
    }
}
 
Example 30
Project: openjdk-jdk10   File: JSR166TestCase.java   View source code 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example 31
Project: guava-mock   File: IteratorsTest.java   View source code 5 votes vote down vote up
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);
}
 
Example 32
Project: googles-monorepo-demo   File: SerializableTesterTest.java   View source code 5 votes vote down vote up
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);
}
 
Example 33
Project: googles-monorepo-demo   File: JSR166TestCase.java   View source code 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example 34
Project: PeSanKita-android   File: SmsListenerTest.java   View source code 5 votes vote down vote up
@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());
  }
}
 
Example 35
Project: googles-monorepo-demo   File: AbstractPackageSanityTests.java   View source code 5 votes vote down vote up
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;
}
 
Example 36
Project: hadoop   File: TestNetUtils.java   View source code 5 votes vote down vote up
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);
  }
}
 
Example 37
Project: parabuild-ci   File: TestViewAsterisks.java   View source code 5 votes vote down vote up
/**
 *  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);
        }
    }
}
 
Example 38
Project: guava-mock   File: SerializableTesterTest.java   View source code 5 votes vote down vote up
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);
}
 
Example 39
Project: guava-mock   File: EqualsTesterTest.java   View source code 5 votes vote down vote up
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");
}
 
Example 40
Project: googles-monorepo-demo   File: ClassSanityTesterTest.java   View source code 5 votes vote down vote up
public void testBadNulls() throws Exception {
  try {
    tester.testNulls(BadNulls.class);
  } catch (AssertionFailedError expected) {
    return;
  }
  fail("should have failed");
}