LUCENE-7009: Add expectThrows utility to LuceneTestCase

This commit is contained in:
Ryan Ernst 2016-02-03 11:02:32 -08:00
parent 61fae32f5f
commit 732b8fb3b9
2 changed files with 28 additions and 0 deletions

View File

@ -110,6 +110,12 @@ Changes in Runtime Behavior
and codec components are no longer allowed to use this extension
(Robert Muir, Mike McCandless)
Tests
* LUCENE-7009: Add expectThrows utility to LuceneTestCase. This uses a lambda
expression to encapsulate a statement that is expected to throw an exception.
(Ryan Ernst)
======================= Lucene 5.5.0 =======================
New Features

View File

@ -64,6 +64,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Logger;
import junit.framework.AssertionFailedError;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
@ -2597,6 +2598,27 @@ public abstract class LuceneTestCase extends Assert {
}
}
/** A runnable that can throw any checked exception. */
@FunctionalInterface
public interface ThrowingRunnable {
void run() throws Throwable;
}
/** Checks a specific exception class is thrown by the given runnable, and returns it. */
public static <T extends Throwable> T expectThrows(Class<T> expectedType, ThrowingRunnable runnable) {
try {
runnable.run();
} catch (Throwable e) {
if (expectedType.isInstance(e)) {
return expectedType.cast(e);
}
AssertionFailedError assertion = new AssertionFailedError("Unexpected exception type, expected " + expectedType.getSimpleName());
assertion.initCause(e);
throw assertion;
}
throw new AssertionFailedError("Expected exception " + expectedType.getSimpleName());
}
/** Returns true if the file exists (can be opened), false
* if it cannot be opened, and (unlike Java's
* File.exists) throws IOException if there's some