Skip to content

Apache Lucene open-source search software

LUCENE-7009: Add expectThrows utility to LuceneTestCase

Ryan Ernst732b8fb3b9d0
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index db58f4d826c..5b2314624ae 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -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
diff --git a/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java
index 717583717c8..c7c45c41c22 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/util/LuceneTestCase.java
@@ -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