Skip to content

Commit

Permalink
Migrate some tests and testing infrastructure from `AssertionFailedEr…
Browse files Browse the repository at this point in the history
…ror` to `AssertionError`.

This is a baby step away from JUnit 3, but my actual motivation was to further take advantage of `AssertionError(String, Throwable)`, which we can now use because it was [added in API Level 19](https://developer.android.com/reference/java/lang/AssertionError#AssertionError(java.lang.String,%20java.lang.Throwable)).

RELNOTES=`testing`: Some test libraries now throw `AssertionError` (instead of the more specific `AssertionFailedError`) in some cases.
PiperOrigin-RevId: 642289963
  • Loading branch information
cpovirk authored and Google Java Core Libraries committed Jun 11, 2024
1 parent c2bbd73 commit fdfbed1
Show file tree
Hide file tree
Showing 22 changed files with 121 additions and 187 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Stack;
import junit.framework.AssertionFailedError;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
Expand Down Expand Up @@ -99,7 +98,7 @@ void assertPermitted(Exception exception) {
+ exception.getClass().getSimpleName()
+ " was thrown; expected "
+ getMessage();
Helpers.fail(exception, message);
throw new AssertionError(message, exception);
}
}

Expand Down Expand Up @@ -355,8 +354,8 @@ private void compareResultsForThisListOfStimuli() {
try {
stimuli[i].executeAndCompare(reference, target);
verify(reference.getElements());
} catch (AssertionFailedError cause) {
Helpers.fail(cause, "failed with stimuli " + subListCopy(stimuli, i + 1));
} catch (AssertionError cause) {
throw new AssertionError("failed with stimuli " + subListCopy(stimuli, i + 1), cause);
}
}
}
Expand Down Expand Up @@ -425,12 +424,12 @@ private <T extends Iterator<E>> void internalExecuteAndCompare(
} catch (PermittedMetaException e) {
referenceException = e;
} catch (UnknownElementException e) {
Helpers.fail(e, e.getMessage());
throw new AssertionError(e);
}

if (referenceException == null) {
if (targetException != null) {
Helpers.fail(targetException, "Target threw exception when reference did not");
throw new AssertionError("Target threw exception when reference did not", targetException);
}

/*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;

import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
Expand All @@ -40,8 +41,6 @@
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
import org.checkerframework.checker.nullness.qual.Nullable;

@GwtCompatible(emulated = true)
Expand Down Expand Up @@ -88,13 +87,13 @@ private static boolean isEmpty(Iterable<?> iterable) {

public static void assertEmpty(Iterable<?> iterable) {
if (!isEmpty(iterable)) {
Assert.fail("Not true that " + iterable + " is empty");
fail("Not true that " + iterable + " is empty");
}
}

public static void assertEmpty(Map<?, ?> map) {
if (!map.isEmpty()) {
Assert.fail("Not true that " + map + " is empty");
fail("Not true that " + map + " is empty");
}
}

Expand All @@ -104,7 +103,7 @@ public static void assertEqualInOrder(Iterable<?> expected, Iterable<?> actual)

while (expectedIter.hasNext() && actualIter.hasNext()) {
if (!equal(expectedIter.next(), actualIter.next())) {
Assert.fail(
fail(
"contents were not equal and in the same order: "
+ "expected = "
+ expected
Expand All @@ -115,7 +114,7 @@ public static void assertEqualInOrder(Iterable<?> expected, Iterable<?> actual)

if (expectedIter.hasNext() || actualIter.hasNext()) {
// actual either had too few or too many elements
Assert.fail(
fail(
"contents were not equal and in the same order: "
+ "expected = "
+ expected
Expand All @@ -139,7 +138,7 @@ public static void assertEqualIgnoringOrder(Iterable<?> expected, Iterable<?> ac
// Yeah it's n^2.
for (Object object : exp) {
if (!act.remove(object)) {
Assert.fail(
fail(
"did not contain expected element "
+ object
+ ", "
Expand Down Expand Up @@ -170,7 +169,7 @@ public static void assertContains(Iterable<?> actual, Object expected) {
}

if (!contained) {
Assert.fail("Not true that " + actual + " contains " + expected);
fail("Not true that " + actual + " contains " + expected);
}
}

Expand All @@ -182,7 +181,7 @@ public static void assertContainsAllOf(Iterable<?> actual, Object... expected) {
}

if (!expectedList.isEmpty()) {
Assert.fail("Not true that " + actual + " contains all of " + Arrays.asList(expected));
fail("Not true that " + actual + " contains all of " + Arrays.asList(expected));
}
}

Expand Down Expand Up @@ -252,12 +251,6 @@ public void remove() {
return iterator.next();
}

static void fail(Throwable cause, Object message) {
AssertionFailedError assertionFailedError = new AssertionFailedError(String.valueOf(message));
assertionFailedError.initCause(cause);
throw assertionFailedError;
}

private static class EntryComparator<K extends @Nullable Object, V extends @Nullable Object>
implements Comparator<Entry<K, V>> {
final @Nullable Comparator<? super K> keyComparator;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,8 @@ static <T> T reserialize(T object) {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()));
return (T) in.readObject();
} catch (IOException | ClassNotFoundException e) {
Helpers.fail(e, e.getMessage());
throw new AssertionError(e);
}
throw new AssertionError("not reachable");
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.junit.Test;

Expand Down Expand Up @@ -307,7 +306,7 @@ protected final void ignoreClasses(Predicate<? super Class<?>> condition) {
this.classFilter = and(this.classFilter, not(condition));
}

private static AssertionFailedError sanityError(
private static AssertionError sanityError(
Class<?> cls, List<String> explicitTestNames, String description, Throwable e) {
String message =
String.format(
Expand All @@ -318,9 +317,7 @@ private static AssertionFailedError sanityError(
cls,
explicitTestNames.get(0),
cls.getName());
AssertionFailedError error = new AssertionFailedError(message);
error.initCause(e);
return error;
return new AssertionError(message, e);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -456,10 +456,7 @@ public FactoryMethodReturnValueTester testNulls() throws Exception {
try {
nullPointerTester.testAllPublicInstanceMethods(instance);
} catch (AssertionError e) {
AssertionError error =
new AssertionFailedError("Null check failed on return value of " + factory);
error.initCause(e);
throw error;
throw new AssertionError("Null check failed on return value of " + factory, e);
}
}
}
Expand Down Expand Up @@ -505,10 +502,8 @@ public FactoryMethodReturnValueTester testSerializable() throws Exception {
try {
SerializableTester.reserialize(instance);
} catch (Exception e) { // sneaky checked exception
AssertionError error =
new AssertionFailedError("Serialization failed on return value of " + factory);
error.initCause(e.getCause());
throw error;
throw new AssertionError(
"Serialization failed on return value of " + factory, e.getCause());
}
}
}
Expand Down Expand Up @@ -537,16 +532,11 @@ public FactoryMethodReturnValueTester testEqualsAndSerializable() throws Excepti
try {
SerializableTester.reserializeAndAssert(instance);
} catch (Exception e) { // sneaky checked exception
AssertionError error =
new AssertionFailedError("Serialization failed on return value of " + factory);
error.initCause(e.getCause());
throw error;
throw new AssertionError(
"Serialization failed on return value of " + factory, e.getCause());
} catch (AssertionFailedError e) {
AssertionError error =
new AssertionFailedError(
"Return value of " + factory + " reserialized to an unequal value");
error.initCause(e);
throw error;
throw new AssertionError(
"Return value of " + factory + " reserialized to an unequal value", e);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
Expand Down Expand Up @@ -377,19 +376,17 @@ private void testParameter(
if (policy.isExpectedType(cause)) {
return;
}
AssertionFailedError error =
new AssertionFailedError(
String.format(
"wrong exception thrown from %s when passing null to %s parameter at index %s.%n"
+ "Full parameters: %s%n"
+ "Actual exception message: %s",
invokable,
invokable.getParameters().get(paramIndex).getType(),
paramIndex,
Arrays.toString(params),
cause));
error.initCause(cause);
throw error;
throw new AssertionError(
String.format(
"wrong exception thrown from %s when passing null to %s parameter at index %s.%n"
+ "Full parameters: %s%n"
+ "Actual exception message: %s",
invokable,
invokable.getParameters().get(paramIndex).getType(),
paramIndex,
Arrays.toString(params),
cause),
cause);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;

/**
Expand Down Expand Up @@ -149,7 +148,7 @@ protected Iterator<Integer> newTargetIterator() {
return new IteratorWithSunJavaBug6529795<>(iterator);
}
}.test();
} catch (AssertionFailedError e) {
} catch (AssertionError e) {
return;
}
fail("Should have caught jdk6 bug in target iterator");
Expand Down Expand Up @@ -201,18 +200,18 @@ protected Iterator<Integer> newTargetIterator() {

@Override
protected void verify(List<Integer> elements) {
throw new AssertionFailedError(message);
throw new AssertionError(message);
}
};
AssertionFailedError actual = null;
AssertionError actual = null;
try {
tester.test();
} catch (AssertionFailedError e) {
} catch (AssertionError e) {
actual = e;
}
assertNotNull("verify() should be able to cause test failure", actual);
assertTrue(
"AssertionFailedError should have info about why test failed",
"AssertionError should have info about why test failed",
actual.getCause().getMessage().contains(message));
}

Expand Down Expand Up @@ -323,7 +322,7 @@ public boolean hasNext() {
private static void assertFailure(IteratorTester<?> tester) {
try {
tester.test();
} catch (AssertionFailedError expected) {
} catch (AssertionError expected) {
return;
}
fail();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import static com.google.common.truth.Truth.assertWithMessage;

import com.google.common.testing.AbstractPackageSanityTests;
import junit.framework.AssertionFailedError;

/**
* Covers basic sanity checks for the entire package.
Expand Down Expand Up @@ -68,7 +67,7 @@ public PackageSanityTests() {
public void testNulls() throws Exception {
try {
super.testNulls();
} catch (AssertionFailedError e) {
} catch (AssertionError e) {
assertWithMessage("Method did not throw null pointer OR element not in graph exception.")
.that(e)
.hasCauseThat()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1208,11 +1208,8 @@ private static int findStackFrame(ExecutionException e, String clazz, String met
return i;
}
}
AssertionFailedError failure =
new AssertionFailedError(
"Expected element " + clazz + "." + method + " not found in stack trace");
failure.initCause(e);
throw failure;
throw new AssertionError(
"Expected element " + clazz + "." + method + " not found in stack trace", e);
}

private ExecutionException getExpectingExecutionException(AbstractFuture<String> future)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,7 @@ public void tearDown() throws Exception {
join();

if (uncaughtThrowable != null) {
throw (AssertionFailedError)
new AssertionFailedError("Uncaught throwable in " + getName())
.initCause(uncaughtThrowable);
throw new AssertionError("Uncaught throwable in " + getName(), uncaughtThrowable);
}
}

Expand Down Expand Up @@ -283,7 +281,7 @@ private static class Response {

Object getResult() {
if (throwable != null) {
throw (AssertionFailedError) new AssertionFailedError().initCause(throwable);
throw new AssertionError(throwable);
}
return result;
}
Expand Down
Loading

0 comments on commit fdfbed1

Please sign in to comment.