Apache Solr open-source search software
LUCENE-7037: Switch all exceptions tests to expectThrows()
Robert Muir189e985b5c14
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ar/TestArabicFilters.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ar/TestArabicFilters.javaindex 7bc9abc9b67..eb2018ffea0 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ar/TestArabicFilters.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ar/TestArabicFilters.java@@ -61,25 +61,19 @@ public class TestArabicFilters extends BaseTokenStreamFactoryTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("ArabicNormalization", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Arabicstem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {charFilterFactory("Persian", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/bg/TestBulgarianStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/bg/TestBulgarianStemFilterFactory.javaindex 7edd86bac23..4b19c94e56d 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/bg/TestBulgarianStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/bg/TestBulgarianStemFilterFactory.java@@ -41,11 +41,9 @@ public class TestBulgarianStemFilterFactory extends BaseTokenStreamFactoryTestCa/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("BulgarianStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/br/TestBrazilianStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/br/TestBrazilianStemFilterFactory.javaindex b3257973285..af47bd24403 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/br/TestBrazilianStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/br/TestBrazilianStemFilterFactory.java@@ -42,11 +42,9 @@ public class TestBrazilianStemFilterFactory extends BaseTokenStreamFactoryTestCa/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("BrazilianStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/charfilter/TestHTMLStripCharFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/charfilter/TestHTMLStripCharFilterFactory.javaindex f3a0b710bde..75b3e87cc1f 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/charfilter/TestHTMLStripCharFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/charfilter/TestHTMLStripCharFilterFactory.java@@ -104,11 +104,9 @@ public class TestHTMLStripCharFilterFactory extends BaseTokenStreamFactoryTestCa/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {charFilterFactory("HTMLStrip", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/charfilter/TestMappingCharFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/charfilter/TestMappingCharFilterFactory.javaindex b1c730f0eb6..e24089cf55b 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/charfilter/TestMappingCharFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/charfilter/TestMappingCharFilterFactory.java@@ -24,11 +24,9 @@ public class TestMappingCharFilterFactory extends BaseTokenStreamFactoryTestCaseMappingCharFilterFactory f = (MappingCharFilterFactory)charFilterFactory("Mapping");- try {- f.parseString( "\\" );- fail( "escape character cannot be alone." );- }- catch (IllegalArgumentException expected) {}+ expectThrows(IllegalArgumentException.class, () -> {+ f.parseString("\\");+ });assertEquals( "unexpected escaped characters","\\\"\n\t\r\b\f", f.parseString( "\\\\\\\"\\n\\t\\r\\b\\f" ) );@@ -37,26 +35,21 @@ public class TestMappingCharFilterFactory extends BaseTokenStreamFactoryTestCaseassertEquals( "unexpected escaped characters","AB", f.parseString( "\\u0041\\u0042" ) );- try {- f.parseString( "\\u000" );- fail( "invalid length check." );- }- catch (IllegalArgumentException expected) {}+ expectThrows(IllegalArgumentException.class, () -> {+ f.parseString("\\u000");+ });- try {- f.parseString( "\\u123x" );- fail( "invalid hex number check." );- }- catch( NumberFormatException expected ){}+ // invalid hex number+ expectThrows(NumberFormatException.class, () -> {+ f.parseString("\\u123x");+ });}/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {charFilterFactory("Mapping", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/cjk/TestCJKBigramFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/cjk/TestCJKBigramFilterFactory.javaindex 6828d5195f6..a917e0c1278 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/cjk/TestCJKBigramFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/cjk/TestCJKBigramFilterFactory.java@@ -60,11 +60,8 @@ public class TestCJKBigramFilterFactory extends BaseTokenStreamFactoryTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("CJKBigram", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/cjk/TestCJKWidthFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/cjk/TestCJKWidthFilterFactory.javaindex c9e80884f30..d4882a90ed2 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/cjk/TestCJKWidthFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/cjk/TestCJKWidthFilterFactory.java@@ -37,11 +37,9 @@ public class TestCJKWidthFilterFactory extends BaseTokenStreamFactoryTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("CJKWidth", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ckb/TestSoraniNormalizationFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ckb/TestSoraniNormalizationFilterFactory.javaindex b1027b29eea..510b83c46fb 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ckb/TestSoraniNormalizationFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ckb/TestSoraniNormalizationFilterFactory.java@@ -38,11 +38,9 @@ public class TestSoraniNormalizationFilterFactory extends BaseTokenStreamFactory/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("SoraniNormalization", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ckb/TestSoraniStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ckb/TestSoraniStemFilterFactory.javaindex 384ea9e56e4..1c4b1623c58 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ckb/TestSoraniStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ckb/TestSoraniStemFilterFactory.java@@ -40,11 +40,9 @@ public class TestSoraniStemFilterFactory extends BaseTokenStreamFactoryTestCase/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("SoraniStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/commongrams/TestCommonGramsFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/commongrams/TestCommonGramsFilterFactory.javaindex e1838b44ecf..98c351ea2d8 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/commongrams/TestCommonGramsFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/commongrams/TestCommonGramsFilterFactory.java@@ -92,11 +92,9 @@ public class TestCommonGramsFilterFactory extends BaseTokenStreamFactoryTestCase/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("CommonGrams", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/commongrams/TestCommonGramsQueryFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/commongrams/TestCommonGramsQueryFilterFactory.javaindex 8ed2e4070b3..7c826a93a00 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/commongrams/TestCommonGramsQueryFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/commongrams/TestCommonGramsQueryFilterFactory.java@@ -91,11 +91,9 @@ public class TestCommonGramsQueryFilterFactory extends BaseTokenStreamFactoryTes/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("CommonGramsQuery", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/compound/TestDictionaryCompoundWordTokenFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/compound/TestDictionaryCompoundWordTokenFilterFactory.javaindex 76532aac929..886251987dc 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/compound/TestDictionaryCompoundWordTokenFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/compound/TestDictionaryCompoundWordTokenFilterFactory.java@@ -44,13 +44,11 @@ public class TestDictionaryCompoundWordTokenFilterFactory extends BaseTokenStrea/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("DictionaryCompoundWord","dictionary", "compoundDictionary.txt","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/compound/TestHyphenationCompoundWordTokenFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/compound/TestHyphenationCompoundWordTokenFilterFactory.javaindex 31f65d33776..0039e2008d7 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/compound/TestHyphenationCompoundWordTokenFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/compound/TestHyphenationCompoundWordTokenFilterFactory.java@@ -67,13 +67,11 @@ public class TestHyphenationCompoundWordTokenFilterFactory extends BaseTokenStre/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("HyphenationCompoundWord","hyphenator", "da_UTF8.xml","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestBugInSomething.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestBugInSomething.javaindex e69d5b859bd..783811ad953 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestBugInSomething.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestBugInSomething.java@@ -138,75 +138,55 @@ public class TestBugInSomething extends BaseTokenStreamTestCase {public void testWrapping() throws Exception {CharFilter cs = new TestRandomChains.CheckThatYouDidntReadAnythingReaderWrapper(wrappedStream);- try {+ Exception expected = expectThrows(Exception.class, () -> {cs.mark(1);- fail();- } catch (Exception e) {- assertEquals("mark(int)", e.getMessage());- }+ });+ assertEquals("mark(int)", expected.getMessage());- try {+ expected = expectThrows(Exception.class, () -> {cs.markSupported();- fail();- } catch (Exception e) {- assertEquals("markSupported()", e.getMessage());- }+ });+ assertEquals("markSupported()", expected.getMessage());- try {+ expected = expectThrows(Exception.class, () -> {cs.read();- fail();- } catch (Exception e) {- assertEquals("read()", e.getMessage());- }+ });+ assertEquals("read()", expected.getMessage());- try {+ expected = expectThrows(Exception.class, () -> {cs.read(new char[0]);- fail();- } catch (Exception e) {- assertEquals("read(char[])", e.getMessage());- }+ });+ assertEquals("read(char[])", expected.getMessage());- try {+ expected = expectThrows(Exception.class, () -> {cs.read(CharBuffer.wrap(new char[0]));- fail();- } catch (Exception e) {- assertEquals("read(CharBuffer)", e.getMessage());- }+ });+ assertEquals("read(CharBuffer)", expected.getMessage());- try {+ expected = expectThrows(Exception.class, () -> {cs.reset();- fail();- } catch (Exception e) {- assertEquals("reset()", e.getMessage());- }+ });+ assertEquals("reset()", expected.getMessage());- try {+ expected = expectThrows(Exception.class, () -> {cs.skip(1);- fail();- } catch (Exception e) {- assertEquals("skip(long)", e.getMessage());- }+ });+ assertEquals("skip(long)", expected.getMessage());- try {+ expected = expectThrows(Exception.class, () -> {cs.correctOffset(1);- fail();- } catch (Exception e) {- assertEquals("correct(int)", e.getMessage());- }+ });+ assertEquals("correct(int)", expected.getMessage());- try {+ expected = expectThrows(Exception.class, () -> {cs.close();- fail();- } catch (Exception e) {- assertEquals("close()", e.getMessage());- }+ });+ assertEquals("close()", expected.getMessage());- try {+ expected = expectThrows(Exception.class, () -> {cs.read(new char[0], 0, 0);- fail();- } catch (Exception e) {- assertEquals("read(char[], int, int)", e.getMessage());- }+ });+ assertEquals("read(char[], int, int)", expected.getMessage());}// todo: test framework?diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestDecimalDigitFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestDecimalDigitFilterFactory.javaindex 112f009cf10..8a484d4b094 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestDecimalDigitFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestDecimalDigitFilterFactory.java@@ -40,11 +40,9 @@ public class TestDecimalDigitFilterFactory extends BaseTokenStreamFactoryTestCas/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("DecimalDigit", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}\ No newline at end of filediff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestStopFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestStopFilterFactory.javaindex 1d0aa8a0690..9fca6b9822f 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestStopFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestStopFilterFactory.java@@ -66,37 +66,33 @@ public class TestStopFilterFactory extends BaseTokenStreamFactoryTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Stop", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}/** Test that bogus arguments result in exception */public void testBogusFormats() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Stop","words", "stop-snowball.txt","format", "bogus");- fail();- } catch (IllegalArgumentException expected) {- String msg = expected.getMessage();- assertTrue(msg, msg.contains("Unknown"));- assertTrue(msg, msg.contains("format"));- assertTrue(msg, msg.contains("bogus"));- }- try {+ });+ String msg = expected.getMessage();+ assertTrue(msg, msg.contains("Unknown"));+ assertTrue(msg, msg.contains("format"));+ assertTrue(msg, msg.contains("bogus"));++ expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Stop",// implicit default words file"format", "bogus");fail();- } catch (IllegalArgumentException expected) {- String msg = expected.getMessage();- assertTrue(msg, msg.contains("can not be specified"));- assertTrue(msg, msg.contains("format"));- assertTrue(msg, msg.contains("bogus"));- }+ });+ msg = expected.getMessage();+ assertTrue(msg, msg.contains("can not be specified"));+ assertTrue(msg, msg.contains("format"));+ assertTrue(msg, msg.contains("bogus"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestTypeTokenFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestTypeTokenFilterFactory.javaindex f7a1f62cfbf..0cfa575445b 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestTypeTokenFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestTypeTokenFilterFactory.java@@ -59,23 +59,19 @@ public class TestTypeTokenFilterFactory extends BaseTokenStreamFactoryTestCase {}public void testMissingTypesParameter() throws Exception {- try {+ // not supplying 'types' parameter should cause an IllegalArgumentException+ expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Type");- fail("not supplying 'types' parameter should cause an IllegalArgumentException");- } catch (IllegalArgumentException e) {- // everything ok- }+ });}/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Type","types", "stoptypes-1.txt","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/custom/TestCustomAnalyzer.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/custom/TestCustomAnalyzer.javaindex 86088c03998..af119275e70 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/custom/TestCustomAnalyzer.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/custom/TestCustomAnalyzer.java@@ -203,15 +203,12 @@ public class TestCustomAnalyzer extends BaseTokenStreamTestCase {assertAnalyzesTo(a, "foo Foo Bar", new String[0]);// try with unmodifiableMap, should fail- try {+ expectThrows(UnsupportedOperationException.class, () -> {CustomAnalyzer.builder().withTokenizer("whitespace").addTokenFilter("stop", stopConfigImmutable).build();- fail();- } catch (UnsupportedOperationException e) {- // pass- }+ });a.close();}@@ -242,133 +239,101 @@ public class TestCustomAnalyzer extends BaseTokenStreamTestCase {// Now test misconfigurations:public void testIncorrectOrder() throws Exception {- try {+ expectThrows(IllegalStateException.class, () -> {CustomAnalyzer.builder().addCharFilter("htmlstrip").withDefaultMatchVersion(Version.LATEST).withTokenizer("whitespace").build();- fail();- } catch (IllegalStateException e) {- // pass- }+ });}public void testMissingSPI() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {CustomAnalyzer.builder().withTokenizer("foobar_nonexistent").build();- fail();- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("SPI"));- assertTrue(e.getMessage().contains("does not exist"));- }+ });+ assertTrue(expected.getMessage().contains("SPI"));+ assertTrue(expected.getMessage().contains("does not exist"));}public void testSetTokenizerTwice() throws Exception {- try {+ expectThrows(AlreadySetException.class, () -> {CustomAnalyzer.builder().withTokenizer("whitespace").withTokenizer(StandardTokenizerFactory.class).build();- fail();- } catch (AlreadySetException e) {- // pass- }+ });}public void testSetMatchVersionTwice() throws Exception {- try {+ expectThrows(AlreadySetException.class, () -> {CustomAnalyzer.builder().withDefaultMatchVersion(Version.LATEST).withDefaultMatchVersion(Version.LATEST).withTokenizer("standard").build();- fail();- } catch (AlreadySetException e) {- // pass- }+ });}public void testSetPosIncTwice() throws Exception {- try {+ expectThrows(AlreadySetException.class, () -> {CustomAnalyzer.builder().withPositionIncrementGap(2).withPositionIncrementGap(3).withTokenizer("standard").build();- fail();- } catch (AlreadySetException e) {- // pass- }+ });}public void testSetOfsGapTwice() throws Exception {- try {+ expectThrows(AlreadySetException.class, () -> {CustomAnalyzer.builder().withOffsetGap(2).withOffsetGap(3).withTokenizer("standard").build();- fail();- } catch (AlreadySetException e) {- // pass- }+ });}public void testNoTokenizer() throws Exception {- try {+ expectThrows(IllegalStateException.class, () -> {CustomAnalyzer.builder().build();- fail();- } catch (IllegalStateException e) {- assertTrue(e.getMessage().equals("You have to set at least a tokenizer."));- }+ });}public void testNullTokenizer() throws Exception {- try {+ expectThrows(NullPointerException.class, () -> {CustomAnalyzer.builder().withTokenizer((String) null).build();- fail();- } catch (NullPointerException e) {- // pass- }+ });}public void testNullTokenizerFactory() throws Exception {- try {+ expectThrows(NullPointerException.class, () -> {CustomAnalyzer.builder().withTokenizer((Class<TokenizerFactory>) null).build();- fail();- } catch (NullPointerException e) {- // pass- }+ });}public void testNullParamKey() throws Exception {- try {+ expectThrows(NullPointerException.class, () -> {CustomAnalyzer.builder().withTokenizer("whitespace", null, "foo").build();- fail();- } catch (NullPointerException e) {- // pass- }+ });}public void testNullMatchVersion() throws Exception {- try {+ expectThrows(NullPointerException.class, () -> {CustomAnalyzer.builder().withDefaultMatchVersion(null).withTokenizer("whitespace").build();- fail();- } catch (NullPointerException e) {- // pass- }+ });}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/cz/TestCzechStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/cz/TestCzechStemFilterFactory.javaindex 81fbfc79f6a..10a36ae3589 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/cz/TestCzechStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/cz/TestCzechStemFilterFactory.java@@ -42,11 +42,9 @@ public class TestCzechStemFilterFactory extends BaseTokenStreamFactoryTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("CzechStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/de/TestGermanLightStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/de/TestGermanLightStemFilterFactory.javaindex 6d52e3b0f8e..5bf6ed01ca6 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/de/TestGermanLightStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/de/TestGermanLightStemFilterFactory.java@@ -37,11 +37,9 @@ public class TestGermanLightStemFilterFactory extends BaseTokenStreamFactoryTest/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("GermanLightStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/de/TestGermanMinimalStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/de/TestGermanMinimalStemFilterFactory.javaindex e571ceaed55..5c85894cc1e 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/de/TestGermanMinimalStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/de/TestGermanMinimalStemFilterFactory.java@@ -39,11 +39,9 @@ public class TestGermanMinimalStemFilterFactory extends BaseTokenStreamFactoryTe/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("GermanMinimalStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/de/TestGermanNormalizationFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/de/TestGermanNormalizationFilterFactory.javaindex 02effb37c84..fd6574624c9 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/de/TestGermanNormalizationFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/de/TestGermanNormalizationFilterFactory.java@@ -39,11 +39,9 @@ public class TestGermanNormalizationFilterFactory extends BaseTokenStreamFactory/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("GermanNormalization", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/de/TestGermanStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/de/TestGermanStemFilterFactory.javaindex 1383ec02d4b..952283a39b7 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/de/TestGermanStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/de/TestGermanStemFilterFactory.java@@ -42,11 +42,9 @@ public class TestGermanStemFilterFactory extends BaseTokenStreamFactoryTestCase/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("GermanStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/el/TestGreekLowerCaseFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/el/TestGreekLowerCaseFilterFactory.javaindex 85d516d69c0..cedc9ab0816 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/el/TestGreekLowerCaseFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/el/TestGreekLowerCaseFilterFactory.java@@ -40,11 +40,9 @@ public class TestGreekLowerCaseFilterFactory extends BaseTokenStreamFactoryTestC/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("GreekLowerCase", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/el/TestGreekStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/el/TestGreekStemFilterFactory.javaindex 75d7c4ce74f..13830e93b7f 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/el/TestGreekStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/el/TestGreekStemFilterFactory.java@@ -38,11 +38,9 @@ public class TestGreekStemFilterFactory extends BaseTokenStreamFactoryTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("GreekStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/en/TestEnglishMinimalStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/en/TestEnglishMinimalStemFilterFactory.javaindex 547a1276be3..e3dc81df600 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/en/TestEnglishMinimalStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/en/TestEnglishMinimalStemFilterFactory.java@@ -37,11 +37,9 @@ public class TestEnglishMinimalStemFilterFactory extends BaseTokenStreamFactoryT/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("EnglishMinimalStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/en/TestKStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/en/TestKStemFilterFactory.javaindex acefd6c4ad9..79fa7cf296b 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/en/TestKStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/en/TestKStemFilterFactory.java@@ -37,11 +37,9 @@ public class TestKStemFilterFactory extends BaseTokenStreamFactoryTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("KStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/en/TestPorterStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/en/TestPorterStemFilterFactory.javaindex dabb39c84a5..a7739b25e10 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/en/TestPorterStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/en/TestPorterStemFilterFactory.java@@ -40,11 +40,9 @@ public class TestPorterStemFilterFactory extends BaseTokenStreamFactoryTestCase/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("PorterStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/es/TestSpanishLightStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/es/TestSpanishLightStemFilterFactory.javaindex f75b5b0f06f..1e038e2aa1a 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/es/TestSpanishLightStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/es/TestSpanishLightStemFilterFactory.java@@ -39,11 +39,9 @@ public class TestSpanishLightStemFilterFactory extends BaseTokenStreamFactoryTes/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("SpanishLightStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/fa/TestPersianNormalizationFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/fa/TestPersianNormalizationFilterFactory.javaindex 0479c00d962..5bffb710a5f 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/fa/TestPersianNormalizationFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/fa/TestPersianNormalizationFilterFactory.java@@ -40,11 +40,9 @@ public class TestPersianNormalizationFilterFactory extends BaseTokenStreamFactor/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("PersianNormalization", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/fi/TestFinnishLightStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/fi/TestFinnishLightStemFilterFactory.javaindex 852e35b7b5f..a433c95c3df 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/fi/TestFinnishLightStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/fi/TestFinnishLightStemFilterFactory.java@@ -39,11 +39,9 @@ public class TestFinnishLightStemFilterFactory extends BaseTokenStreamFactoryTes/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("FinnishLightStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/fr/TestFrenchLightStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/fr/TestFrenchLightStemFilterFactory.javaindex cb5737617da..15a2b96732b 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/fr/TestFrenchLightStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/fr/TestFrenchLightStemFilterFactory.java@@ -37,11 +37,9 @@ public class TestFrenchLightStemFilterFactory extends BaseTokenStreamFactoryTest/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("FrenchLightStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/fr/TestFrenchMinimalStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/fr/TestFrenchMinimalStemFilterFactory.javaindex d5790b695ba..6cd399b5951 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/fr/TestFrenchMinimalStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/fr/TestFrenchMinimalStemFilterFactory.java@@ -37,11 +37,9 @@ public class TestFrenchMinimalStemFilterFactory extends BaseTokenStreamFactoryTe/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("FrenchMinimalStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ga/TestIrishLowerCaseFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ga/TestIrishLowerCaseFilterFactory.javaindex d5d96bf6e9d..20149360cc5 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ga/TestIrishLowerCaseFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ga/TestIrishLowerCaseFilterFactory.java@@ -37,11 +37,9 @@ public class TestIrishLowerCaseFilterFactory extends BaseTokenStreamFactoryTestC/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("IrishLowerCase", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/gl/TestGalicianMinimalStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/gl/TestGalicianMinimalStemFilterFactory.javaindex 4fb75bd9cf5..ddc60f02962 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/gl/TestGalicianMinimalStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/gl/TestGalicianMinimalStemFilterFactory.java@@ -37,11 +37,9 @@ public class TestGalicianMinimalStemFilterFactory extends BaseTokenStreamFactory/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("GalicianMinimalStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/gl/TestGalicianStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/gl/TestGalicianStemFilterFactory.javaindex ef3242e2410..e02fc5c91b0 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/gl/TestGalicianStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/gl/TestGalicianStemFilterFactory.java@@ -37,11 +37,9 @@ public class TestGalicianStemFilterFactory extends BaseTokenStreamFactoryTestCas/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("GalicianStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hi/TestHindiFilters.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hi/TestHindiFilters.javaindex bdf4087fcd4..8caf70030d1 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hi/TestHindiFilters.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hi/TestHindiFilters.java@@ -64,25 +64,19 @@ public class TestHindiFilters extends BaseTokenStreamFactoryTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("IndicNormalization", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("HindiNormalization", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("HindiStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hu/TestHungarianLightStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hu/TestHungarianLightStemFilterFactory.javaindex 53a1832f224..b595067f09f 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hu/TestHungarianLightStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hu/TestHungarianLightStemFilterFactory.java@@ -37,11 +37,9 @@ public class TestHungarianLightStemFilterFactory extends BaseTokenStreamFactoryT/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("HungarianLightStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestDictionary.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestDictionary.javaindex 455a111befa..4f044074744 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestDictionary.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestDictionary.java@@ -131,13 +131,11 @@ public class TestDictionary extends LuceneTestCase {InputStream dictStream = getClass().getResourceAsStream("simple.dic");Directory tempDir = getDirectory();- try {+ ParseException expected = expectThrows(ParseException.class, () -> {new Dictionary(tempDir, "dictionary", affixStream, dictStream);- fail("didn't get expected exception");- } catch (ParseException expected) {- assertTrue(expected.getMessage().startsWith("The affix file contains a rule with less than four elements"));- assertEquals(24, expected.getErrorOffset());- }+ });+ assertTrue(expected.getMessage().startsWith("The affix file contains a rule with less than four elements"));+ assertEquals(24, expected.getErrorOffset());affixStream.close();dictStream.close();@@ -150,12 +148,10 @@ public class TestDictionary extends LuceneTestCase {InputStream dictStream = getClass().getResourceAsStream("simple.dic");Directory tempDir = getDirectory();- try {+ Exception expected = expectThrows(Exception.class, () -> {new Dictionary(tempDir, "dictionary", affixStream, dictStream);- fail("didn't get expected exception");- } catch (Exception expected) {- assertTrue(expected.getMessage().startsWith("expected only one flag"));- }+ });+ assertTrue(expected.getMessage().startsWith("expected only one flag"));affixStream.close();dictStream.close();diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestHunspellStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestHunspellStemFilterFactory.javaindex 77a5d34c8b5..7c445521fd4 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestHunspellStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestHunspellStemFilterFactory.java@@ -38,13 +38,11 @@ public class TestHunspellStemFilterFactory extends BaseTokenStreamFactoryTestCas/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("HunspellStem","dictionary", "simple.dic","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/id/TestIndonesianStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/id/TestIndonesianStemFilterFactory.javaindex 5b5c11ca764..ad382ecc31d 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/id/TestIndonesianStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/id/TestIndonesianStemFilterFactory.java@@ -53,11 +53,9 @@ public class TestIndonesianStemFilterFactory extends BaseTokenStreamFactoryTestC/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("IndonesianStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/it/TestItalianLightStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/it/TestItalianLightStemFilterFactory.javaindex c809f611de9..a9d763ffbcc 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/it/TestItalianLightStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/it/TestItalianLightStemFilterFactory.java@@ -37,11 +37,9 @@ public class TestItalianLightStemFilterFactory extends BaseTokenStreamFactoryTes/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("ItalianLightStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/lv/TestLatvianStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/lv/TestLatvianStemFilterFactory.javaindex fd0220d0dd3..8ccdbafdd4d 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/lv/TestLatvianStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/lv/TestLatvianStemFilterFactory.java@@ -39,11 +39,9 @@ public class TestLatvianStemFilterFactory extends BaseTokenStreamFactoryTestCase/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("LatvianStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/DateRecognizerFilterFactoryTest.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/DateRecognizerFilterFactoryTest.javaindex 8d15e18cdef..739f78f4fe4 100755--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/DateRecognizerFilterFactoryTest.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/DateRecognizerFilterFactoryTest.java@@ -24,14 +24,11 @@ import org.apache.lucene.analysis.BaseTokenStreamTestCase;public class DateRecognizerFilterFactoryTest extends BaseTokenStreamTestCase {public void testBadLanguageTagThrowsException() {- try {+ expectThrows(Exception.class, () -> {final Map<String,String> args = new HashMap<>();args.put(DateRecognizerFilterFactory.LOCALE, "en_US");new DateRecognizerFilterFactory(args);- fail("Bad language tag should have thrown an exception");- } catch (Exception e) {- // expected;- }+ });}public void testGoodLocaleParsesWell() {diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestCapitalizationFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestCapitalizationFilterFactory.javaindex 3581c087e33..1a4f7267d76 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestCapitalizationFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestCapitalizationFilterFactory.java@@ -264,12 +264,10 @@ public class TestCapitalizationFilterFactory extends BaseTokenStreamFactoryTestC/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Capitalization", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}/**@@ -277,7 +275,7 @@ public class TestCapitalizationFilterFactory extends BaseTokenStreamFactoryTestC*/public void testInvalidArguments() throws Exception {for (final String arg : new String[]{"minWordLength", "maxTokenLength", "maxWordCount"}) {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {Reader reader = new StringReader("foo foobar super-duper-trooper");TokenStream stream = whitespaceMockTokenizer(reader);@@ -287,11 +285,9 @@ public class TestCapitalizationFilterFactory extends BaseTokenStreamFactoryTestCarg, "-3","okPrefix", "McK","forceFirstLetter", "true").create(stream);- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains(arg + " must be greater than or equal to zero")- || expected.getMessage().contains(arg + " must be greater than zero"));- }+ });+ assertTrue(expected.getMessage().contains(arg + " must be greater than or equal to zero") ||+ expected.getMessage().contains(arg + " must be greater than zero"));}}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestCodepointCountFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestCodepointCountFilterFactory.javaindex 026d1b7879d..985b309f52c 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestCodepointCountFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestCodepointCountFilterFactory.java@@ -39,29 +39,25 @@ public class TestCodepointCountFilterFactory extends BaseTokenStreamFactoryTestC/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("CodepointCount","min", "4","max", "5","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}/** Test that invalid arguments result in exception */public void testInvalidArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {Reader reader = new StringReader("foo foobar super-duper-trooper");TokenStream stream = new MockTokenizer(MockTokenizer.WHITESPACE, false);((Tokenizer)stream).setReader(reader);tokenFilterFactory("CodepointCount",CodepointCountFilterFactory.MIN_KEY, "5",CodepointCountFilterFactory.MAX_KEY, "4").create(stream);- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("maximum length must not be greater than minimum length"));- }+ });+ assertTrue(expected.getMessage().contains("maximum length must not be greater than minimum length"));}}\ No newline at end of filediff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestFingerprintFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestFingerprintFilterFactory.javaindex 766429f0c36..ed2bd3ee54d 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestFingerprintFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestFingerprintFilterFactory.java@@ -50,13 +50,11 @@ public class TestFingerprintFilterFactory extends BaseTokenStreamFactoryTestCase* Test that bogus arguments result in exception*/public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Fingerprint",FingerprintFilterFactory.MAX_OUTPUT_TOKEN_SIZE_KEY, "3","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestKeepFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestKeepFilterFactory.javaindex 387ff5b8dbd..6110e2b2152 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestKeepFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestKeepFilterFactory.java@@ -44,11 +44,9 @@ public class TestKeepFilterFactory extends BaseTokenStreamFactoryTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("KeepWord", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}\ No newline at end of filediff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestKeywordMarkerFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestKeywordMarkerFilterFactory.javaindex 0de8882fb1b..7bdf151f715 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestKeywordMarkerFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestKeywordMarkerFilterFactory.java@@ -93,11 +93,9 @@ public class TestKeywordMarkerFilterFactory extends BaseTokenStreamFactoryTestCa/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("KeywordMarker", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLengthFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLengthFilterFactory.javaindex 6e754ef8058..183d95f8823 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLengthFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLengthFilterFactory.java@@ -39,29 +39,25 @@ public class TestLengthFilterFactory extends BaseTokenStreamFactoryTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Length",LengthFilterFactory.MIN_KEY, "4",LengthFilterFactory.MAX_KEY, "5","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}/** Test that invalid arguments result in exception */public void testInvalidArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {Reader reader = new StringReader("foo foobar super-duper-trooper");TokenStream stream = new MockTokenizer(MockTokenizer.WHITESPACE, false);((Tokenizer)stream).setReader(reader);tokenFilterFactory("Length",LengthFilterFactory.MIN_KEY, "5",LengthFilterFactory.MAX_KEY, "4").create(stream);- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("maximum length must not be greater than minimum length"));- }+ });+ assertTrue(expected.getMessage().contains("maximum length must not be greater than minimum length"));}}\ No newline at end of filediff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLimitTokenCountFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLimitTokenCountFilterFactory.javaindex 41b2a357958..1f32994b195 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLimitTokenCountFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLimitTokenCountFilterFactory.java@@ -43,26 +43,22 @@ public class TestLimitTokenCountFilterFactory extends BaseTokenStreamFactoryTestpublic void testRequired() throws Exception {// param is required- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("LimitTokenCount");- fail();- } catch (IllegalArgumentException e) {- assertTrue("exception doesn't mention param: " + e.getMessage(),- 0 < e.getMessage().indexOf(LimitTokenCountFilterFactory.MAX_TOKEN_COUNT_KEY));- }+ });+ assertTrue("exception doesn't mention param: " + expected.getMessage(),+ 0 < expected.getMessage().indexOf(LimitTokenCountFilterFactory.MAX_TOKEN_COUNT_KEY));}/*** Test that bogus arguments result in exception*/public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("LimitTokenCount",LimitTokenCountFilterFactory.MAX_TOKEN_COUNT_KEY, "3","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLimitTokenOffsetFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLimitTokenOffsetFilterFactory.javaindex eaef6768c51..3840b9e309f 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLimitTokenOffsetFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLimitTokenOffsetFilterFactory.java@@ -43,26 +43,22 @@ public class TestLimitTokenOffsetFilterFactory extends BaseTokenStreamFactoryTespublic void testRequired() throws Exception {// param is required- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("LimitTokenOffset");- fail();- } catch (IllegalArgumentException e) {- assertTrue("exception doesn't mention param: " + e.getMessage(),- 0 < e.getMessage().indexOf(LimitTokenOffsetFilterFactory.MAX_START_OFFSET));- }+ });+ assertTrue("exception doesn't mention param: " + expected.getMessage(),+ 0 < expected.getMessage().indexOf(LimitTokenOffsetFilterFactory.MAX_START_OFFSET));}/*** Test that bogus arguments result in exception*/public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("LimitTokenOffset",LimitTokenOffsetFilterFactory.MAX_START_OFFSET, "3","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLimitTokenPositionFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLimitTokenPositionFilterFactory.javaindex a537af40c5f..014cc88e955 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLimitTokenPositionFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLimitTokenPositionFilterFactory.java@@ -41,13 +41,11 @@ public class TestLimitTokenPositionFilterFactory extends BaseTokenStreamFactoryT}public void testMissingParam() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("LimitTokenPosition");- fail();- } catch (IllegalArgumentException e) {- assertTrue("exception doesn't mention param: " + e.getMessage(),- 0 < e.getMessage().indexOf(LimitTokenPositionFilterFactory.MAX_TOKEN_POSITION_KEY));- }+ });+ assertTrue("exception doesn't mention param: " + expected.getMessage(),+ 0 < expected.getMessage().indexOf(LimitTokenPositionFilterFactory.MAX_TOKEN_POSITION_KEY));}public void testMaxPosition1WithShingles() throws Exception {@@ -73,13 +71,11 @@ public class TestLimitTokenPositionFilterFactory extends BaseTokenStreamFactoryT* Test that bogus arguments result in exception*/public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("LimitTokenPosition","maxTokenPosition", "3","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestRemoveDuplicatesTokenFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestRemoveDuplicatesTokenFilterFactory.javaindex 8b1c77fcc46..3b771f4b3f9 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestRemoveDuplicatesTokenFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestRemoveDuplicatesTokenFilterFactory.java@@ -50,11 +50,9 @@ public class TestRemoveDuplicatesTokenFilterFactory extends BaseTokenStreamFacto/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("RemoveDuplicates", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestScandinavianFoldingFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestScandinavianFoldingFilterFactory.javaindex 9811bbacc18..969e89195da 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestScandinavianFoldingFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestScandinavianFoldingFilterFactory.java@@ -33,12 +33,10 @@ public class TestScandinavianFoldingFilterFactory extends BaseTokenStreamFactory/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("ScandinavianFolding","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}\ No newline at end of filediff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestScandinavianNormalizationFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestScandinavianNormalizationFilterFactory.javaindex 65c3b822019..f4dd48c1330 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestScandinavianNormalizationFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestScandinavianNormalizationFilterFactory.java@@ -29,12 +29,10 @@ public class TestScandinavianNormalizationFilterFactory extends BaseTokenStreamF/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("ScandinavianNormalization","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}\ No newline at end of filediff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestStemmerOverrideFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestStemmerOverrideFilterFactory.javaindex ed2631f7d34..395f3439045 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestStemmerOverrideFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestStemmerOverrideFilterFactory.java@@ -55,11 +55,9 @@ public class TestStemmerOverrideFilterFactory extends BaseTokenStreamFactoryTest/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("StemmerOverride", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestTrimFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestTrimFilterFactory.javaindex 986bc1c3f62..e52e61ab1b5 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestTrimFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestTrimFilterFactory.java@@ -37,11 +37,9 @@ public class TestTrimFilterFactory extends BaseTokenStreamFactoryTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Trim", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestTruncateTokenFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestTruncateTokenFilterFactory.javaindex 29f75baf4ae..d0e74c936f5 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestTruncateTokenFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestTruncateTokenFilterFactory.java@@ -45,28 +45,24 @@ public class TestTruncateTokenFilterFactory extends BaseTokenStreamFactoryTestCa* Test that bogus arguments result in exception*/public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Truncate",TruncateTokenFilterFactory.PREFIX_LENGTH_KEY, "5","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameter(s):"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameter(s):"));}/*** Test that negative prefix length result in exception*/public void testNonPositivePrefixLengthArgument() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Truncate",TruncateTokenFilterFactory.PREFIX_LENGTH_KEY, "-5");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains(TruncateTokenFilterFactory.PREFIX_LENGTH_KEY + " parameter must be a positive number: -5"));- }+ });+ assertTrue(expected.getMessage().contains(TruncateTokenFilterFactory.PREFIX_LENGTH_KEY + " parameter must be a positive number: -5"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/EdgeNGramTokenFilterTest.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/EdgeNGramTokenFilterTest.javaindex 3d0877fd445..d7536e7050f 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/EdgeNGramTokenFilterTest.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/EdgeNGramTokenFilterTest.java@@ -49,33 +49,21 @@ public class EdgeNGramTokenFilterTest extends BaseTokenStreamTestCase {}public void testInvalidInput() throws Exception {- boolean gotException = false;- try {+ expectThrows(IllegalArgumentException.class, () -> {new EdgeNGramTokenFilter(input, 0, 0);- } catch (IllegalArgumentException e) {- gotException = true;- }- assertTrue(gotException);+ });}public void testInvalidInput2() throws Exception {- boolean gotException = false;- try {+ expectThrows(IllegalArgumentException.class, () -> {new EdgeNGramTokenFilter(input, 2, 1);- } catch (IllegalArgumentException e) {- gotException = true;- }- assertTrue(gotException);+ });}public void testInvalidInput3() throws Exception {- boolean gotException = false;- try {+ expectThrows(IllegalArgumentException.class, () -> {new EdgeNGramTokenFilter(input, -1, 2);- } catch (IllegalArgumentException e) {- gotException = true;- }- assertTrue(gotException);+ });}public void testFrontUnigram() throws Exception {diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/EdgeNGramTokenizerTest.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/EdgeNGramTokenizerTest.javaindex c7ca4fef352..7fbea5f8d60 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/EdgeNGramTokenizerTest.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/EdgeNGramTokenizerTest.java@@ -42,33 +42,21 @@ public class EdgeNGramTokenizerTest extends BaseTokenStreamTestCase {}public void testInvalidInput() throws Exception {- boolean gotException = false;- try {+ expectThrows(IllegalArgumentException.class, () -> {new EdgeNGramTokenizer(0, 0).setReader(input);- } catch (IllegalArgumentException e) {- gotException = true;- }- assertTrue(gotException);+ });}public void testInvalidInput2() throws Exception {- boolean gotException = false;- try {+ expectThrows(IllegalArgumentException.class, () -> {new EdgeNGramTokenizer(2, 1).setReader(input);- } catch (IllegalArgumentException e) {- gotException = true;- }- assertTrue(gotException);+ });}public void testInvalidInput3() throws Exception {- boolean gotException = false;- try {+ expectThrows(IllegalArgumentException.class, () -> {new EdgeNGramTokenizer(-1, 2).setReader(input);- } catch (IllegalArgumentException e) {- gotException = true;- }- assertTrue(gotException);+ });}public void testFrontUnigram() throws Exception {diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/NGramTokenFilterTest.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/NGramTokenFilterTest.javaindex 834933a78a1..d8591a9726e 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/NGramTokenFilterTest.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/NGramTokenFilterTest.java@@ -47,23 +47,15 @@ public class NGramTokenFilterTest extends BaseTokenStreamTestCase {}public void testInvalidInput() throws Exception {- boolean gotException = false;- try {+ expectThrows(IllegalArgumentException.class, () -> {new NGramTokenFilter(input, 2, 1);- } catch (IllegalArgumentException e) {- gotException = true;- }- assertTrue(gotException);+ });}public void testInvalidInput2() throws Exception {- boolean gotException = false;- try {+ expectThrows(IllegalArgumentException.class, () -> {new NGramTokenFilter(input, 0, 1);- } catch (IllegalArgumentException e) {- gotException = true;- }- assertTrue(gotException);+ });}public void testUnigrams() throws Exception {diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/NGramTokenizerTest.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/NGramTokenizerTest.javaindex 8655f3da9c9..46a0c1c143e 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/NGramTokenizerTest.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/NGramTokenizerTest.java@@ -46,25 +46,16 @@ public class NGramTokenizerTest extends BaseTokenStreamTestCase {}public void testInvalidInput() throws Exception {- boolean gotException = false;- try {+ expectThrows(IllegalArgumentException.class, () -> {NGramTokenizer tok = new NGramTokenizer(2, 1);- tok.setReader(input);- } catch (IllegalArgumentException e) {- gotException = true;- }- assertTrue(gotException);+ });}public void testInvalidInput2() throws Exception {- boolean gotException = false;- try {+ expectThrows(IllegalArgumentException.class, () -> {NGramTokenizer tok = new NGramTokenizer(0, 1);tok.setReader(input);- } catch (IllegalArgumentException e) {- gotException = true;- }- assertTrue(gotException);+ });}public void testUnigrams() throws Exception {diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/TestNGramFilters.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/TestNGramFilters.javaindex d429f61e73b..12433526f6e 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/TestNGramFilters.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ngram/TestNGramFilters.java@@ -126,32 +126,24 @@ public class TestNGramFilters extends BaseTokenStreamFactoryTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenizerFactory("NGram", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {tokenizerFactory("EdgeNGram", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("NGram", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("EdgeNGram", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/no/TestNorwegianLightStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/no/TestNorwegianLightStemFilterFactory.javaindex 6f7f8760a50..cd2bc2fe595 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/no/TestNorwegianLightStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/no/TestNorwegianLightStemFilterFactory.java@@ -53,11 +53,9 @@ public class TestNorwegianLightStemFilterFactory extends BaseTokenStreamFactoryT/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("NorwegianLightStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/no/TestNorwegianMinimalStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/no/TestNorwegianMinimalStemFilterFactory.javaindex c433b763998..91d021b8a0c 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/no/TestNorwegianMinimalStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/no/TestNorwegianMinimalStemFilterFactory.java@@ -57,11 +57,9 @@ public class TestNorwegianMinimalStemFilterFactory extends BaseTokenStreamFactor/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("NorwegianMinimalStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/pattern/TestPatternReplaceCharFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/pattern/TestPatternReplaceCharFilterFactory.javaindex f1c555306c8..624de9e2cb6 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/pattern/TestPatternReplaceCharFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/pattern/TestPatternReplaceCharFilterFactory.java@@ -71,13 +71,11 @@ public class TestPatternReplaceCharFilterFactory extends BaseTokenStreamFactoryT/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {charFilterFactory("PatternReplace","pattern", "something","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/pattern/TestPatternReplaceFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/pattern/TestPatternReplaceFilterFactory.javaindex 24f751a422b..80ced7abab4 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/pattern/TestPatternReplaceFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/pattern/TestPatternReplaceFilterFactory.java@@ -42,13 +42,11 @@ public class TestPatternReplaceFilterFactory extends BaseTokenStreamFactoryTestC/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("PatternReplace","pattern", "something","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/pattern/TestPatternTokenizerFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/pattern/TestPatternTokenizerFactory.javaindex a0d1af4f4ea..02126f165f2 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/pattern/TestPatternTokenizerFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/pattern/TestPatternTokenizerFactory.java@@ -36,13 +36,11 @@ public class TestPatternTokenizerFactory extends BaseTokenStreamFactoryTestCase/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenizerFactory("Pattern","pattern", "something","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/payloads/TestDelimitedPayloadTokenFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/payloads/TestDelimitedPayloadTokenFilterFactory.javaindex a9bec99af8d..65f5b72bd7b 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/payloads/TestDelimitedPayloadTokenFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/payloads/TestDelimitedPayloadTokenFilterFactory.java@@ -70,14 +70,12 @@ public class TestDelimitedPayloadTokenFilterFactory extends BaseTokenStreamFacto/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("DelimitedPayload","encoder", "float","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/pt/TestPortugueseLightStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/pt/TestPortugueseLightStemFilterFactory.javaindex 0af152ad23b..5db7a596888 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/pt/TestPortugueseLightStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/pt/TestPortugueseLightStemFilterFactory.java@@ -39,11 +39,9 @@ public class TestPortugueseLightStemFilterFactory extends BaseTokenStreamFactory/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("PortugueseLightStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/pt/TestPortugueseMinimalStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/pt/TestPortugueseMinimalStemFilterFactory.javaindex 5ad28b500f3..4fe74bb7567 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/pt/TestPortugueseMinimalStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/pt/TestPortugueseMinimalStemFilterFactory.java@@ -39,11 +39,9 @@ public class TestPortugueseMinimalStemFilterFactory extends BaseTokenStreamFacto/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("PortugueseMinimalStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/pt/TestPortugueseStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/pt/TestPortugueseStemFilterFactory.javaindex e00ba793c19..d07d7942650 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/pt/TestPortugueseStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/pt/TestPortugueseStemFilterFactory.java@@ -37,11 +37,9 @@ public class TestPortugueseStemFilterFactory extends BaseTokenStreamFactoryTestC/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("PortugueseStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/reverse/TestReverseStringFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/reverse/TestReverseStringFilterFactory.javaindex 72b2b336ea8..874095c2a5f 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/reverse/TestReverseStringFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/reverse/TestReverseStringFilterFactory.java@@ -40,11 +40,9 @@ public class TestReverseStringFilterFactory extends BaseTokenStreamFactoryTestCa/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("ReverseString", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ru/TestRussianLightStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ru/TestRussianLightStemFilterFactory.javaindex bf82ea8c4c4..244c6fde257 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/ru/TestRussianLightStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/ru/TestRussianLightStemFilterFactory.java@@ -37,11 +37,9 @@ public class TestRussianLightStemFilterFactory extends BaseTokenStreamFactoryTes/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("RussianLightStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/shingle/TestShingleFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/shingle/TestShingleFilterFactory.javaindex aed5f0bd106..2c894edeed9 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/shingle/TestShingleFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/shingle/TestShingleFilterFactory.java@@ -217,11 +217,9 @@ public class TestShingleFilterFactory extends BaseTokenStreamFactoryTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Shingle", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/snowball/TestSnowballPorterFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/snowball/TestSnowballPorterFilterFactory.javaindex 6dc1104f0c2..5696bf38639 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/snowball/TestSnowballPorterFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/snowball/TestSnowballPorterFilterFactory.java@@ -60,12 +60,10 @@ public class TestSnowballPorterFilterFactory extends BaseTokenStreamFactoryTestC/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("SnowballPorter", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/sr/TestSerbianNormalizationFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/sr/TestSerbianNormalizationFilterFactory.javaindex 8c45ed0a015..772f6fc0118 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/sr/TestSerbianNormalizationFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/sr/TestSerbianNormalizationFilterFactory.java@@ -47,12 +47,10 @@ public class TestSerbianNormalizationFilterFactory extends BaseTokenStreamFactor/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("SerbianNormalization", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/standard/TestStandardFactories.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/standard/TestStandardFactories.javaindex 17d3468e430..00796783cb8 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/standard/TestStandardFactories.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/standard/TestStandardFactories.java@@ -149,60 +149,44 @@ public class TestStandardFactories extends BaseTokenStreamFactoryTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenizerFactory("Standard", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {tokenizerFactory("Classic", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {tokenizerFactory("Whitespace", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {tokenizerFactory("Letter", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {tokenizerFactory("LowerCase", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("ASCIIFolding", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Standard", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Classic", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/standard/TestUAX29URLEmailTokenizerFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/standard/TestUAX29URLEmailTokenizerFactory.javaindex f2034645d92..12a48651780 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/standard/TestUAX29URLEmailTokenizerFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/standard/TestUAX29URLEmailTokenizerFactory.java@@ -165,20 +165,16 @@ public class TestUAX29URLEmailTokenizerFactory extends BaseTokenStreamFactoryTes/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenizerFactory("UAX29URLEmail", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}- public void testIllegalArguments() throws Exception {- try {+ public void testIllegalArguments() throws Exception {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenizerFactory("UAX29URLEmail", "maxTokenLength", "-1").create();- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("maxTokenLength must be greater than zero"));- }+ });+ assertTrue(expected.getMessage().contains("maxTokenLength must be greater than zero"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/sv/TestSwedishLightStemFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/sv/TestSwedishLightStemFilterFactory.javaindex 04e946b2e7c..7c4f55821e3 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/sv/TestSwedishLightStemFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/sv/TestSwedishLightStemFilterFactory.java@@ -36,11 +36,9 @@ public class TestSwedishLightStemFilterFactory extends BaseTokenStreamFactoryTes/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("SwedishLightStem", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSolrSynonymParser.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSolrSynonymParser.javaindex a7e2da9e20d..9467137e4a5 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSolrSynonymParser.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSolrSynonymParser.java@@ -77,12 +77,9 @@ public class TestSolrSynonymParser extends BaseSynonymParserTestCase {String testFile = "a => b => c";Analyzer analyzer = new MockAnalyzer(random());SolrSynonymParser parser = new SolrSynonymParser(true, true, analyzer);- try {+ expectThrows(ParseException.class, () -> {parser.parse(new StringReader(testFile));- fail("didn't get expected exception");- } catch (ParseException expected) {- // expected exc- }+ });analyzer.close();}@@ -91,12 +88,9 @@ public class TestSolrSynonymParser extends BaseSynonymParserTestCase {String testFile = "a => 1";Analyzer analyzer = new MockAnalyzer(random(), MockTokenizer.SIMPLE, false);SolrSynonymParser parser = new SolrSynonymParser(true, true, analyzer);- try {+ expectThrows(ParseException.class, () -> {parser.parse(new StringReader(testFile));- fail("didn't get expected exception");- } catch (ParseException expected) {- // expected exc- }+ });analyzer.close();}@@ -105,12 +99,9 @@ public class TestSolrSynonymParser extends BaseSynonymParserTestCase {String testFile = "1 => a";Analyzer analyzer = new MockAnalyzer(random(), MockTokenizer.SIMPLE, false);SolrSynonymParser parser = new SolrSynonymParser(true, true, analyzer);- try {+ expectThrows(ParseException.class, () -> {parser.parse(new StringReader(testFile));- fail("didn't get expected exception");- } catch (ParseException expected) {- // expected exc- }+ });analyzer.close();}@@ -119,12 +110,9 @@ public class TestSolrSynonymParser extends BaseSynonymParserTestCase {String testFile = "testola => the test";Analyzer analyzer = new EnglishAnalyzer();SolrSynonymParser parser = new SolrSynonymParser(true, true, analyzer);- try {+ expectThrows(ParseException.class, () -> {parser.parse(new StringReader(testFile));- fail("didn't get expected exception");- } catch (ParseException expected) {- // expected exc- }+ });analyzer.close();}@@ -133,12 +121,9 @@ public class TestSolrSynonymParser extends BaseSynonymParserTestCase {String testFile = "the test => testola";Analyzer analyzer = new EnglishAnalyzer();SolrSynonymParser parser = new SolrSynonymParser(true, true, analyzer);- try {+ expectThrows(ParseException.class, () -> {parser.parse(new StringReader(testFile));- fail("didn't get expected exception");- } catch (ParseException expected) {- // expected exc- }+ });analyzer.close();}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSynonymFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSynonymFilterFactory.javaindex eedf25b1227..e3bb00ab607 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSynonymFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSynonymFilterFactory.java@@ -76,14 +76,12 @@ public class TestSynonymFilterFactory extends BaseTokenStreamFactoryTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Synonym","synonyms", "synonyms.txt","bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}/** Test that analyzer and tokenizerFactory is both specified */@@ -97,15 +95,13 @@ public class TestSynonymFilterFactory extends BaseTokenStreamFactoryTestCase {"analyzer", analyzer);assertNotNull(factory);- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Synonym","synonyms", "synonyms.txt","analyzer", analyzer,"tokenizerFactory", tokenizerFactory);- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Analyzer and TokenizerFactory can't be specified both"));- }+ });+ assertTrue(expected.getMessage().contains("Analyzer and TokenizerFactory can't be specified both"));}static final String TOK_SYN_ARG_VAL = "argument";@@ -132,27 +128,21 @@ public class TestSynonymFilterFactory extends BaseTokenStreamFactoryTestCase {assertNotNull(factory);// sanity check that sub-PatternTokenizerFactory fails w/o pattern- try {- factory = tokenFilterFactory("Synonym",+ expectThrows(Exception.class, () -> {+ tokenFilterFactory("Synonym","synonyms", "synonyms.txt","tokenizerFactory", clazz);- fail("tokenizerFactory should have complained about missing pattern arg");- } catch (Exception expected) {- // :NOOP:- }+ });// sanity check that sub-PatternTokenizerFactory fails on unexpected- try {- factory = tokenFilterFactory("Synonym",+ expectThrows(Exception.class, () -> {+ tokenFilterFactory("Synonym","synonyms", "synonyms.txt","tokenizerFactory", clazz,"tokenizerFactory.pattern", "(.*)","tokenizerFactory.bogusbogusbogus", "bogus","tokenizerFactory.group", "0");- fail("tokenizerFactory should have complained about missing pattern arg");- } catch (Exception expected) {- // :NOOP:- }+ });}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSynonymMapFilter.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSynonymMapFilter.javaindex 9e1c09503bb..0fbbd2e58cc 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSynonymMapFilter.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSynonymMapFilter.java@@ -946,12 +946,9 @@ public class TestSynonymMapFilter extends BaseTokenStreamTestCase {public void testEmpty() throws Exception {Tokenizer tokenizer = new MockTokenizer();tokenizer.setReader(new StringReader("aa bb"));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new SynonymFilter(tokenizer, new SynonymMap.Builder(true).build(), true);- fail("did not hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- assertEquals("fst must be non-null", iae.getMessage());- }+ });+ assertEquals("fst must be non-null", expected.getMessage());}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/th/TestThaiTokenizerFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/th/TestThaiTokenizerFactory.javaindex f8bf8a6b8ae..428c36a43e5 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/th/TestThaiTokenizerFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/th/TestThaiTokenizerFactory.java@@ -40,11 +40,9 @@ public class TestThaiTokenizerFactory extends BaseTokenStreamFactoryTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {assumeTrue("JRE does not support Thai dictionary-based BreakIterator", ThaiTokenizer.DBBI_AVAILABLE);- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenizerFactory("Thai", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/tr/TestApostropheFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/tr/TestApostropheFilterFactory.javaindex f87446790f4..b4ecc1c4d51 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/tr/TestApostropheFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/tr/TestApostropheFilterFactory.java@@ -45,11 +45,9 @@ public class TestApostropheFilterFactory extends BaseTokenStreamFactoryTestCase* Test that bogus arguments result in exception*/public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Apostrophe", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameter(s):"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameter(s):"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/tr/TestTurkishLowerCaseFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/tr/TestTurkishLowerCaseFilterFactory.javaindex 12a829d8ae9..9b1638f3f7e 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/tr/TestTurkishLowerCaseFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/tr/TestTurkishLowerCaseFilterFactory.java@@ -42,11 +42,9 @@ public class TestTurkishLowerCaseFilterFactory extends BaseTokenStreamFactoryTes/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("TurkishLowerCase", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestAnalysisSPILoader.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestAnalysisSPILoader.javaindex 3e47fe2d1f2..098b98b0410 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestAnalysisSPILoader.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestAnalysisSPILoader.java@@ -42,19 +42,13 @@ public class TestAnalysisSPILoader extends LuceneTestCase {}public void testBogusLookupTokenizer() {- try {+ expectThrows(IllegalArgumentException.class, () -> {TokenizerFactory.forName("sdfsdfsdfdsfsdfsdf", new HashMap<String,String>());- fail();- } catch (IllegalArgumentException expected) {- //- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {TokenizerFactory.forName("!(**#$U*#$*", new HashMap<String,String>());- fail();- } catch (IllegalArgumentException expected) {- //- }+ });}public void testLookupTokenizerClass() {@@ -64,19 +58,13 @@ public class TestAnalysisSPILoader extends LuceneTestCase {}public void testBogusLookupTokenizerClass() {- try {+ expectThrows(IllegalArgumentException.class, () -> {TokenizerFactory.lookupClass("sdfsdfsdfdsfsdfsdf");- fail();- } catch (IllegalArgumentException expected) {- //- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {TokenizerFactory.lookupClass("!(**#$U*#$*");- fail();- } catch (IllegalArgumentException expected) {- //- }+ });}public void testAvailableTokenizers() {@@ -94,19 +82,13 @@ public class TestAnalysisSPILoader extends LuceneTestCase {}public void testBogusLookupTokenFilter() {- try {+ expectThrows(IllegalArgumentException.class, () -> {TokenFilterFactory.forName("sdfsdfsdfdsfsdfsdf", new HashMap<String,String>());- fail();- } catch (IllegalArgumentException expected) {- //- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {TokenFilterFactory.forName("!(**#$U*#$*", new HashMap<String,String>());- fail();- } catch (IllegalArgumentException expected) {- //- }+ });}public void testLookupTokenFilterClass() {@@ -120,19 +102,13 @@ public class TestAnalysisSPILoader extends LuceneTestCase {}public void testBogusLookupTokenFilterClass() {- try {+ expectThrows(IllegalArgumentException.class, () -> {TokenFilterFactory.lookupClass("sdfsdfsdfdsfsdfsdf");- fail();- } catch (IllegalArgumentException expected) {- //- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {TokenFilterFactory.lookupClass("!(**#$U*#$*");- fail();- } catch (IllegalArgumentException expected) {- //- }+ });}public void testAvailableTokenFilters() {@@ -147,19 +123,13 @@ public class TestAnalysisSPILoader extends LuceneTestCase {}public void testBogusLookupCharFilter() {- try {+ expectThrows(IllegalArgumentException.class, () -> {CharFilterFactory.forName("sdfsdfsdfdsfsdfsdf", new HashMap<String,String>());- fail();- } catch (IllegalArgumentException expected) {- //- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {CharFilterFactory.forName("!(**#$U*#$*", new HashMap<String,String>());- fail();- } catch (IllegalArgumentException expected) {- //- }+ });}public void testLookupCharFilterClass() {@@ -169,19 +139,13 @@ public class TestAnalysisSPILoader extends LuceneTestCase {}public void testBogusLookupCharFilterClass() {- try {+ expectThrows(IllegalArgumentException.class, () -> {CharFilterFactory.lookupClass("sdfsdfsdfdsfsdfsdf");- fail();- } catch (IllegalArgumentException expected) {- //- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {CharFilterFactory.lookupClass("!(**#$U*#$*");- fail();- } catch (IllegalArgumentException expected) {- //- }+ });}public void testAvailableCharFilters() {diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestCharArrayIterator.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestCharArrayIterator.javaindex e39fa07ca83..0287a7ce53e 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestCharArrayIterator.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestCharArrayIterator.java@@ -140,12 +140,9 @@ public class TestCharArrayIterator extends LuceneTestCase {// setIndex()ci.setText("test".toCharArray(), 0, "test".length());- try {+ expectThrows(IllegalArgumentException.class, () -> {ci.setIndex(5);- fail();- } catch (Exception e) {- assertTrue(e instanceof IllegalArgumentException);- }+ });// clone()char text[] = "testing".toCharArray();diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestCharArrayMap.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestCharArrayMap.javaindex a926543a2fc..66b0dce1ac3 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestCharArrayMap.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestCharArrayMap.java@@ -87,12 +87,11 @@ public class TestCharArrayMap extends LuceneTestCase {cs.clear();assertEquals(0, cs.size());assertEquals(0, cm.size());- try {+ // keySet() should not allow adding new keys+ expectThrows(UnsupportedOperationException.class, () -> {cs.add("test");- fail("keySet() allows adding new keys");- } catch (UnsupportedOperationException ue) {- // pass- }+ });+cm.putAll(hm);assertEquals(hm.size(), cs.size());assertEquals(cm.size(), cs.size());@@ -131,6 +130,7 @@ public class TestCharArrayMap extends LuceneTestCase {assertTrue(cm.isEmpty());}+ // TODO: break this up into simpler test methods vs. "telling a story"public void testModifyOnUnmodifiable(){CharArrayMap<Integer> map = new CharArrayMap<>(2, false);map.put("foo",1);diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestCharArraySet.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestCharArraySet.javaindex 04b211becbc..1fcee6519cf 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestCharArraySet.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestCharArraySet.java@@ -86,6 +86,7 @@ public class TestCharArraySet extends LuceneTestCase {assertTrue(set.contains(TEST_STOP_WORDS[i]));}+ // TODO: break this up into simpler test methods, vs "telling a story"public void testModifyOnUnmodifiable(){CharArraySet set=new CharArraySet(10, true);set.addAll(Arrays.asList(TEST_STOP_WORDS));@@ -185,12 +186,9 @@ public class TestCharArraySet extends LuceneTestCase {assertTrue(set.contains("1"));assertTrue(set.contains(new char[]{'1'}));- try{+ expectThrows(NullPointerException.class, () -> {CharArraySet.unmodifiableSet(null);- fail("can not make null unmodifiable");- }catch (NullPointerException e) {- // expected- }+ });}public void testSupplementaryChars() {@@ -408,18 +406,18 @@ public class TestCharArraySet extends LuceneTestCase {*/public void testContainsWithNull() {CharArraySet set = new CharArraySet(1, true);- try {++ expectThrows(NullPointerException.class, () -> {set.contains((char[]) null, 0, 10);- fail("null value must raise NPE");- } catch (NullPointerException e) {}- try {+ });++ expectThrows(NullPointerException.class, () -> {set.contains((CharSequence) null);- fail("null value must raise NPE");- } catch (NullPointerException e) {}- try {+ });++ expectThrows(NullPointerException.class, () -> {set.contains((Object) null);- fail("null value must raise NPE");- } catch (NullPointerException e) {}+ });}public void testToString() {diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestCharacterUtils.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestCharacterUtils.javaindex 758862911b6..2faeec7d93d 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestCharacterUtils.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestCharacterUtils.java@@ -40,23 +40,18 @@ public class TestCharacterUtils extends LuceneTestCase {assertEquals((int) 'A', java4.codePointAt(cpAt3, 0));assertEquals((int) '\ud801', java4.codePointAt(cpAt3, 3));assertEquals((int) '\ud801', java4.codePointAt(highSurrogateAt3, 3));- try {+ expectThrows(IndexOutOfBoundsException.class, () -> {java4.codePointAt(highSurrogateAt3, 4);- fail("string index out of bounds");- } catch (IndexOutOfBoundsException e) {- }+ });CharacterUtils java5 = CharacterUtils.getInstance();assertEquals((int) 'A', java5.codePointAt(cpAt3, 0));assertEquals(Character.toCodePoint('\ud801', '\udc1c'), java5.codePointAt(cpAt3, 3));assertEquals((int) '\ud801', java5.codePointAt(highSurrogateAt3, 3));- try {+ expectThrows(IndexOutOfBoundsException.class, () -> {java5.codePointAt(highSurrogateAt3, 4);- fail("string index out of bounds");- } catch (IndexOutOfBoundsException e) {- }-+ });}@Test@@ -149,11 +144,10 @@ public class TestCharacterUtils extends LuceneTestCase {assertEquals(0, newCharacterBuffer.getOffset());assertEquals(0, newCharacterBuffer.getLength());- try {- newCharacterBuffer = CharacterUtils.newCharacterBuffer(1);- fail("length must be >= 2");- } catch (IllegalArgumentException e) {- }+ // length must be >= 2+ expectThrows(IllegalArgumentException.class, () -> {+ CharacterUtils.newCharacterBuffer(1);+ });}@Testdiff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestElisionFilterFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestElisionFilterFactory.javaindex d48db628f8c..8b81a8934a0 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestElisionFilterFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestElisionFilterFactory.java@@ -65,11 +65,9 @@ public class TestElisionFilterFactory extends BaseTokenStreamFactoryTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenFilterFactory("Elision", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestFilesystemResourceLoader.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestFilesystemResourceLoader.javaindex 3143964b612..be906115bd0 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestFilesystemResourceLoader.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/util/TestFilesystemResourceLoader.java@@ -30,18 +30,15 @@ import org.apache.lucene.util.LuceneTestCase;public class TestFilesystemResourceLoader extends LuceneTestCase {private void assertNotFound(ResourceLoader rl) throws Exception {- try {+ // the resource does not exist, should fail!+ expectThrows(IOException.class, () -> {IOUtils.closeWhileHandlingException(rl.openResource("this-directory-really-really-really-should-not-exist/foo/bar.txt"));- fail("The resource does not exist, should fail!");- } catch (IOException ioe) {- // pass- }- try {+ });++ // the class does not exist, should fail!+ expectThrows(RuntimeException.class, () -> {rl.newInstance("org.apache.lucene.analysis.FooBarFilterFactory", TokenFilterFactory.class);- fail("The class does not exist, should fail!");- } catch (RuntimeException iae) {- // pass- }+ });}private void assertClasspathDelegation(ResourceLoader rl) throws Exception {diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/wikipedia/TestWikipediaTokenizerFactory.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/wikipedia/TestWikipediaTokenizerFactory.javaindex aa0e5ec79dc..ec345f9bcdc 100644--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/wikipedia/TestWikipediaTokenizerFactory.java+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/wikipedia/TestWikipediaTokenizerFactory.java@@ -42,11 +42,9 @@ public class TestWikipediaTokenizerFactory extends BaseTokenStreamFactoryTestCas/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {tokenizerFactory("Wikipedia", "bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUFoldingFilterFactory.java b/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUFoldingFilterFactory.javaindex 719ad20e5ce..4c1d4ac0eb2 100644--- a/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUFoldingFilterFactory.java+++ b/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUFoldingFilterFactory.java@@ -39,13 +39,11 @@ public class TestICUFoldingFilterFactory extends BaseTokenStreamTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new ICUFoldingFilterFactory(new HashMap<String,String>() {{put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUNormalizer2CharFilterFactory.java b/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUNormalizer2CharFilterFactory.javaindex da817777fc4..90055f15f0d 100644--- a/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUNormalizer2CharFilterFactory.java+++ b/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUNormalizer2CharFilterFactory.java@@ -38,14 +38,12 @@ public class TestICUNormalizer2CharFilterFactory extends BaseTokenStreamTestCase/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new ICUNormalizer2CharFilterFactory(new HashMap<String,String>() {{put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}// TODO: add tests for different formsdiff --git a/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUNormalizer2FilterFactory.java b/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUNormalizer2FilterFactory.javaindex 90a14f36328..5533215d317 100644--- a/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUNormalizer2FilterFactory.java+++ b/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUNormalizer2FilterFactory.java@@ -39,14 +39,12 @@ public class TestICUNormalizer2FilterFactory extends BaseTokenStreamTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new ICUNormalizer2FilterFactory(new HashMap<String,String>() {{put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}// TODO: add tests for different formsdiff --git a/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUTransformFilterFactory.java b/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUTransformFilterFactory.javaindex b74984ce801..a47821778b0 100644--- a/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUTransformFilterFactory.java+++ b/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/TestICUTransformFilterFactory.java@@ -66,14 +66,12 @@ public class TestICUTransformFilterFactory extends BaseTokenStreamTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new ICUTransformFilterFactory(new HashMap<String,String>() {{put("id", "Null");put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/segmentation/TestCharArrayIterator.java b/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/segmentation/TestCharArrayIterator.javaindex 14d7f0f27de..28856fb2438 100644--- a/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/segmentation/TestCharArrayIterator.java+++ b/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/segmentation/TestCharArrayIterator.java@@ -86,12 +86,9 @@ public class TestCharArrayIterator extends LuceneTestCase {public void testSetIndex() {CharArrayIterator ci = new CharArrayIterator();ci.setText("test".toCharArray(), 0, "test".length());- try {+ expectThrows(IllegalArgumentException.class, () -> {ci.setIndex(5);- fail();- } catch (Exception e) {- assertTrue(e instanceof IllegalArgumentException);- }+ });}public void testClone() {diff --git a/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/segmentation/TestICUTokenizerFactory.java b/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/segmentation/TestICUTokenizerFactory.javaindex e288c4df32f..f44e7459c64 100644--- a/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/segmentation/TestICUTokenizerFactory.java+++ b/lucene/analysis/icu/src/test/org/apache/lucene/analysis/icu/segmentation/TestICUTokenizerFactory.java@@ -92,13 +92,11 @@ public class TestICUTokenizerFactory extends BaseTokenStreamTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new ICUTokenizerFactory(new HashMap<String,String>() {{put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseBaseFormFilterFactory.java b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseBaseFormFilterFactory.javaindex b140516d662..e52d98cf81f 100644--- a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseBaseFormFilterFactory.java+++ b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseBaseFormFilterFactory.java@@ -43,13 +43,11 @@ public class TestJapaneseBaseFormFilterFactory extends BaseTokenStreamTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new JapaneseBaseFormFilterFactory(new HashMap<String,String>() {{put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseIterationMarkCharFilterFactory.java b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseIterationMarkCharFilterFactory.javaindex fe5ae6659c7..e14c822964e 100644--- a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseIterationMarkCharFilterFactory.java+++ b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseIterationMarkCharFilterFactory.java@@ -91,13 +91,11 @@ public class TestJapaneseIterationMarkCharFilterFactory extends BaseTokenStreamT/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new JapaneseIterationMarkCharFilterFactory(new HashMap<String,String>() {{put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseKatakanaStemFilterFactory.java b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseKatakanaStemFilterFactory.javaindex 6a112e76a0f..39c7a178016 100644--- a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseKatakanaStemFilterFactory.java+++ b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseKatakanaStemFilterFactory.java@@ -43,13 +43,11 @@ public class TestJapaneseKatakanaStemFilterFactory extends BaseTokenStreamTestCa/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new JapaneseKatakanaStemFilterFactory(new HashMap<String,String>() {{put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseNumberFilterFactory.java b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseNumberFilterFactory.javaindex 44e32346dce..a92d3f036b0 100644--- a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseNumberFilterFactory.java+++ b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseNumberFilterFactory.java@@ -50,13 +50,11 @@ public class TestJapaneseNumberFilterFactory extends BaseTokenStreamTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new JapaneseNumberFilterFactory(new HashMap<String,String>() {{put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapanesePartOfSpeechStopFilterFactory.java b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapanesePartOfSpeechStopFilterFactory.javaindex 979fd7f67f1..501d2fca408 100644--- a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapanesePartOfSpeechStopFilterFactory.java+++ b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapanesePartOfSpeechStopFilterFactory.java@@ -53,14 +53,12 @@ public class TestJapanesePartOfSpeechStopFilterFactory extends BaseTokenStreamTe/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new JapanesePartOfSpeechStopFilterFactory(new HashMap<String,String>() {{put("luceneMatchVersion", Version.LATEST.toString());put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseReadingFormFilterFactory.java b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseReadingFormFilterFactory.javaindex 1b12ec1710c..266fd01a14b 100644--- a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseReadingFormFilterFactory.java+++ b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseReadingFormFilterFactory.java@@ -42,13 +42,11 @@ public class TestJapaneseReadingFormFilterFactory extends BaseTokenStreamTestCas/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new JapaneseReadingFormFilterFactory(new HashMap<String,String>() {{put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseTokenizerFactory.java b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseTokenizerFactory.javaindex 45bf6034c1c..bdf22cf9e48 100644--- a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseTokenizerFactory.java+++ b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseTokenizerFactory.java@@ -111,14 +111,12 @@ public class TestJapaneseTokenizerFactory extends BaseTokenStreamTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new JapaneseTokenizerFactory(new HashMap<String,String>() {{put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}private TokenStream makeTokenStream(HashMap<String, String> args, String in) throws IOException {diff --git a/lucene/analysis/morfologik/src/test/org/apache/lucene/analysis/morfologik/TestMorfologikFilterFactory.java b/lucene/analysis/morfologik/src/test/org/apache/lucene/analysis/morfologik/TestMorfologikFilterFactory.javaindex 9a597fc3af1..d971dbdf551 100644--- a/lucene/analysis/morfologik/src/test/org/apache/lucene/analysis/morfologik/TestMorfologikFilterFactory.java+++ b/lucene/analysis/morfologik/src/test/org/apache/lucene/analysis/morfologik/TestMorfologikFilterFactory.java@@ -75,26 +75,22 @@ public class TestMorfologikFilterFactory extends BaseTokenStreamTestCase {public void testMissingDictionary() throws Exception {final ResourceLoader loader = new ClasspathResourceLoader(TestMorfologikFilterFactory.class);- try {+ IOException expected = expectThrows(IOException.class, () -> {Map<String,String> params = new HashMap<>();params.put(MorfologikFilterFactory.DICTIONARY_ATTRIBUTE, "missing-dictionary-resource.dict");MorfologikFilterFactory factory = new MorfologikFilterFactory(params);factory.inform(loader);- fail();- } catch (IOException e) {- assertTrue(e.getMessage().contains("Resource not found"));- }+ });+ assertTrue(expected.getMessage().contains("Resource not found"));}/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {HashMap<String,String> params = new HashMap<String,String>();params.put("bogusArg", "bogusValue");new MorfologikFilterFactory(params);- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/phonetic/src/test/org/apache/lucene/analysis/phonetic/TestBeiderMorseFilterFactory.java b/lucene/analysis/phonetic/src/test/org/apache/lucene/analysis/phonetic/TestBeiderMorseFilterFactory.javaindex c29a9b43425..5c9887eb8e0 100644--- a/lucene/analysis/phonetic/src/test/org/apache/lucene/analysis/phonetic/TestBeiderMorseFilterFactory.java+++ b/lucene/analysis/phonetic/src/test/org/apache/lucene/analysis/phonetic/TestBeiderMorseFilterFactory.java@@ -62,13 +62,11 @@ public class TestBeiderMorseFilterFactory extends BaseTokenStreamTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new BeiderMorseFilterFactory(new HashMap<String,String>() {{put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/phonetic/src/test/org/apache/lucene/analysis/phonetic/TestDaitchMokotoffSoundexFilterFactory.java b/lucene/analysis/phonetic/src/test/org/apache/lucene/analysis/phonetic/TestDaitchMokotoffSoundexFilterFactory.javaindex b73deb356ba..bdac2adbb0d 100644--- a/lucene/analysis/phonetic/src/test/org/apache/lucene/analysis/phonetic/TestDaitchMokotoffSoundexFilterFactory.java+++ b/lucene/analysis/phonetic/src/test/org/apache/lucene/analysis/phonetic/TestDaitchMokotoffSoundexFilterFactory.java@@ -53,13 +53,11 @@ public class TestDaitchMokotoffSoundexFilterFactory extends BaseTokenStreamTestC/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new DaitchMokotoffSoundexFilterFactory(new HashMap<String,String>() {{put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/phonetic/src/test/org/apache/lucene/analysis/phonetic/TestDoubleMetaphoneFilterFactory.java b/lucene/analysis/phonetic/src/test/org/apache/lucene/analysis/phonetic/TestDoubleMetaphoneFilterFactory.javaindex 24c8e1460d4..6f707427a55 100644--- a/lucene/analysis/phonetic/src/test/org/apache/lucene/analysis/phonetic/TestDoubleMetaphoneFilterFactory.java+++ b/lucene/analysis/phonetic/src/test/org/apache/lucene/analysis/phonetic/TestDoubleMetaphoneFilterFactory.java@@ -53,13 +53,11 @@ public class TestDoubleMetaphoneFilterFactory extends BaseTokenStreamTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new DoubleMetaphoneFilterFactory(new HashMap<String,String>() {{put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/phonetic/src/test/org/apache/lucene/analysis/phonetic/TestPhoneticFilterFactory.java b/lucene/analysis/phonetic/src/test/org/apache/lucene/analysis/phonetic/TestPhoneticFilterFactory.javaindex ff20b652caa..f2050767f1b 100644--- a/lucene/analysis/phonetic/src/test/org/apache/lucene/analysis/phonetic/TestPhoneticFilterFactory.java+++ b/lucene/analysis/phonetic/src/test/org/apache/lucene/analysis/phonetic/TestPhoneticFilterFactory.java@@ -64,36 +64,30 @@ public class TestPhoneticFilterFactory extends BaseTokenStreamTestCase {* Case: Failures and Exceptions*/public void testMissingEncoder() throws IOException {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new PhoneticFilterFactory(new HashMap<String,String>());- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Configuration Error: missing parameter 'encoder'"));- }+ });+ assertTrue(expected.getMessage().contains("Configuration Error: missing parameter 'encoder'"));}public void testUnknownEncoder() throws IOException {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {Map<String,String> args = new HashMap<>();args.put("encoder", "XXX");PhoneticFilterFactory factory = new PhoneticFilterFactory(args);factory.inform(new ClasspathResourceLoader(factory.getClass()));- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Error loading encoder"));- }+ });+ assertTrue(expected.getMessage().contains("Error loading encoder"));}public void testUnknownEncoderReflection() throws IOException {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {Map<String,String> args = new HashMap<>();args.put("encoder", "org.apache.commons.codec.language.NonExistence");PhoneticFilterFactory factory = new PhoneticFilterFactory(args);factory.inform(new ClasspathResourceLoader(factory.getClass()));- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Error loading encoder"));- }+ });+ assertTrue(expected.getMessage().contains("Error loading encoder"));}/**@@ -172,15 +166,13 @@ public class TestPhoneticFilterFactory extends BaseTokenStreamTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new PhoneticFilterFactory(new HashMap<String,String>() {{put("encoder", "Metaphone");put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}static void assertAlgorithm(String algName, String inject, String input,diff --git a/lucene/analysis/smartcn/src/test/org/apache/lucene/analysis/cn/smart/TestHMMChineseTokenizerFactory.java b/lucene/analysis/smartcn/src/test/org/apache/lucene/analysis/cn/smart/TestHMMChineseTokenizerFactory.javaindex e16a4fe628d..c3294862dea 100644--- a/lucene/analysis/smartcn/src/test/org/apache/lucene/analysis/cn/smart/TestHMMChineseTokenizerFactory.java+++ b/lucene/analysis/smartcn/src/test/org/apache/lucene/analysis/cn/smart/TestHMMChineseTokenizerFactory.java@@ -44,13 +44,11 @@ public class TestHMMChineseTokenizerFactory extends BaseTokenStreamTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new HMMChineseTokenizerFactory(new HashMap<String,String>() {{put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/stempel/src/test/org/apache/lucene/analysis/stempel/TestStempelPolishStemFilterFactory.java b/lucene/analysis/stempel/src/test/org/apache/lucene/analysis/stempel/TestStempelPolishStemFilterFactory.javaindex cfb022bd61d..7199755aae2 100644--- a/lucene/analysis/stempel/src/test/org/apache/lucene/analysis/stempel/TestStempelPolishStemFilterFactory.java+++ b/lucene/analysis/stempel/src/test/org/apache/lucene/analysis/stempel/TestStempelPolishStemFilterFactory.java@@ -40,13 +40,11 @@ public class TestStempelPolishStemFilterFactory extends BaseTokenStreamTestCase/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new StempelPolishStemFilterFactory(new HashMap<String,String>() {{put("bogusArg", "bogusValue");}});- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}}diff --git a/lucene/analysis/uima/src/test/org/apache/lucene/analysis/uima/ae/OverridingParamsAEProviderTest.java b/lucene/analysis/uima/src/test/org/apache/lucene/analysis/uima/ae/OverridingParamsAEProviderTest.javaindex 8f7e1118e11..923210bb077 100644--- a/lucene/analysis/uima/src/test/org/apache/lucene/analysis/uima/ae/OverridingParamsAEProviderTest.java+++ b/lucene/analysis/uima/src/test/org/apache/lucene/analysis/uima/ae/OverridingParamsAEProviderTest.java@@ -17,6 +17,7 @@package org.apache.lucene.analysis.uima.ae;+import org.apache.lucene.util.LuceneTestCase;import org.apache.uima.analysis_engine.AnalysisEngine;import org.apache.uima.resource.ResourceInitializationException;import org.junit.Test;@@ -24,24 +25,17 @@ import org.junit.Test;import java.util.HashMap;import java.util.Map;-import static org.junit.Assert.assertEquals;-import static org.junit.Assert.assertNotNull;-import static org.junit.Assert.fail;-/*** TestCase for {@link OverridingParamsAEProvider}*/-public class OverridingParamsAEProviderTest {+public class OverridingParamsAEProviderTest extends LuceneTestCase {@Testpublic void testNullMapInitialization() throws Exception {- try {+ expectThrows(ResourceInitializationException.class, () -> {AEProvider aeProvider = new OverridingParamsAEProvider("/uima/TestEntityAnnotatorAE.xml", null);aeProvider.getAE();- fail("should fail due to null Map passed");- } catch (ResourceInitializationException e) {- // everything ok- }+ });}@Testdiff --git a/lucene/backward-codecs/src/test/org/apache/lucene/index/TestMaxPositionInOldIndex.java b/lucene/backward-codecs/src/test/org/apache/lucene/index/TestMaxPositionInOldIndex.javaindex 37f8c21e0c3..87625d20674 100644--- a/lucene/backward-codecs/src/test/org/apache/lucene/index/TestMaxPositionInOldIndex.java+++ b/lucene/backward-codecs/src/test/org/apache/lucene/index/TestMaxPositionInOldIndex.java@@ -81,13 +81,10 @@ public class BuildMaxPositionIndex {TestUtil.unzip(resource, path);BaseDirectoryWrapper dir = newFSDirectory(path);dir.setCheckIndexOnClose(false);- try {+ RuntimeException expected = expectThrows(RuntimeException.class, () -> {TestUtil.checkIndex(dir, false, true);- fail("corruption was not detected");- } catch (RuntimeException re) {- // expected- assertTrue(re.getMessage().contains("pos 2147483647 > IndexWriter.MAX_POSITION=2147483519"));- }+ });+ assertTrue(expected.getMessage().contains("pos 2147483647 > IndexWriter.MAX_POSITION=2147483519"));// Also confirm merging detects this:IndexWriterConfig iwc = newIndexWriterConfig();@@ -95,14 +92,13 @@ public class BuildMaxPositionIndex {iwc.setMergePolicy(newLogMergePolicy());IndexWriter w = new IndexWriter(dir, iwc);w.addDocument(new Document());- try {+ CorruptIndexException expectedCorruption = expectThrows(CorruptIndexException.class, () -> {w.forceMerge(1);- } catch (CorruptIndexException cie) {- assertEquals(cie.getMessage(), new CorruptIndexException(cie.getOriginalMessage(), cie.getResourceDescription()).getMessage());- // SerialMergeScheduler- assertTrue("got message " + cie.getMessage(),- cie.getMessage().contains("position=2147483647 is too large (> IndexWriter.MAX_POSITION=2147483519), field=\"foo\" doc=0 (resource=PerFieldPostings(segment=_0 formats=1)"));- }+ });+ assertEquals(expectedCorruption.getMessage(), new CorruptIndexException(expectedCorruption.getOriginalMessage(), expectedCorruption.getResourceDescription()).getMessage());+ // SerialMergeScheduler+ assertTrue("got message " + expectedCorruption.getMessage(),+ expectedCorruption.getMessage().contains("position=2147483647 is too large (> IndexWriter.MAX_POSITION=2147483519), field=\"foo\" doc=0 (resource=PerFieldPostings(segment=_0 formats=1)"));w.close();dir.close();diff --git a/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/TestPerfTasksLogic.java b/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/TestPerfTasksLogic.javaindex b9b19579dee..5dbf6609585 100644--- a/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/TestPerfTasksLogic.java+++ b/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/TestPerfTasksLogic.java@@ -258,13 +258,9 @@ public class TestPerfTasksLogic extends BenchmarkTestCase {CountingHighlighterTestTask.numHighlightedResults = 0;CountingHighlighterTestTask.numDocsRetrieved = 0;// 3. execute the algorithm (required in every "logic" test)- try {- Benchmark benchmark = execBenchmark(algLines);- assertTrue("CountingHighlighterTest should have thrown an exception", false);- assertNotNull(benchmark); // (avoid compile warning on unused variable)- } catch (Exception e) {- assertTrue(true);- }+ expectThrows(Exception.class, () -> {+ execBenchmark(algLines);+ });}/**diff --git a/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/feeds/EnwikiContentSourceTest.java b/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/feeds/EnwikiContentSourceTest.javaindex c6fa60fe78a..9e76700153a 100644--- a/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/feeds/EnwikiContentSourceTest.java+++ b/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/feeds/EnwikiContentSourceTest.java@@ -56,12 +56,9 @@ public class EnwikiContentSourceTest extends LuceneTestCase {}private void assertNoMoreDataException(EnwikiContentSource stdm) throws Exception {- try {+ expectThrows(NoMoreDataException.class, () -> {stdm.getNextDocData(null);- fail("Expecting NoMoreDataException");- } catch (NoMoreDataException e) {- // expected- }+ });}private final String PAGE1 =diff --git a/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/feeds/LineDocSourceTest.java b/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/feeds/LineDocSourceTest.javaindex 99236cd27a7..197ce4aefcc 100644--- a/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/feeds/LineDocSourceTest.java+++ b/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/feeds/LineDocSourceTest.java@@ -214,12 +214,9 @@ public class LineDocSourceTest extends BenchmarkTestCase {writer.write(testCases[i]);writer.newLine();writer.close();- try {+ expectThrows(Exception.class, () -> {doIndexAndSearchTest(file, null, null);- fail("Some exception should have been thrown for: [" + testCases[i] + "]");- } catch (Exception e) {- // expected.- }+ });}}diff --git a/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/feeds/TrecContentSourceTest.java b/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/feeds/TrecContentSourceTest.javaindex bb87fdd9e3e..12574222523 100644--- a/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/feeds/TrecContentSourceTest.java+++ b/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/feeds/TrecContentSourceTest.java@@ -75,13 +75,9 @@ public class TrecContentSourceTest extends LuceneTestCase {}private void assertNoMoreDataException(StringableTrecSource stdm) throws Exception {- boolean thrown = false;- try {+ expectThrows(NoMoreDataException.class, () -> {stdm.getNextDocData(null);- } catch (NoMoreDataException e) {- thrown = true;- }- assertTrue("Expecting NoMoreDataException", thrown);+ });}public void testOneDocument() throws Exception {diff --git a/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/tasks/alt/AltPackageTaskTest.java b/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/tasks/alt/AltPackageTaskTest.javaindex 059650d1050..4e9972dfa1b 100644--- a/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/tasks/alt/AltPackageTaskTest.java+++ b/lucene/benchmark/src/test/org/apache/lucene/benchmark/byTask/tasks/alt/AltPackageTaskTest.java@@ -25,12 +25,9 @@ public class AltPackageTaskTest extends BenchmarkTestCase {/** Benchmark should fail loading the algorithm when alt is not specified */public void testWithoutAlt() throws Exception {- try {+ expectThrows(Exception.class, () -> {execBenchmark(altAlg(false));- assertFalse("Should have failed to run the algorithm",true);- } catch(Exception e) {- // expected exception, do nothing- }+ });}/** Benchmark should be able to load the algorithm when alt is specified */diff --git a/lucene/codecs/src/test/org/apache/lucene/codecs/autoprefix/TestAutoPrefixTerms.java b/lucene/codecs/src/test/org/apache/lucene/codecs/autoprefix/TestAutoPrefixTerms.javaindex 726c3f0a419..316fc9a5709 100644--- a/lucene/codecs/src/test/org/apache/lucene/codecs/autoprefix/TestAutoPrefixTerms.java+++ b/lucene/codecs/src/test/org/apache/lucene/codecs/autoprefix/TestAutoPrefixTerms.java@@ -648,11 +648,10 @@ public class TestAutoPrefixTerms extends LuceneTestCase {Document doc = new Document();doc.add(new Field("foo", "bar bar", ft));w.addDocument(doc);- try {+ IllegalStateException expected = expectThrows(IllegalStateException.class, () -> {w.commit();- } catch (IllegalStateException ise) {- assertEquals("ranges can only be indexed with IndexOptions.DOCS (field: foo)", ise.getMessage());- }+ });+ assertEquals("ranges can only be indexed with IndexOptions.DOCS (field: foo)", expected.getMessage());w.close();dir.close();}@@ -668,11 +667,11 @@ public class TestAutoPrefixTerms extends LuceneTestCase {Document doc = new Document();doc.add(new Field("foo", "bar bar", ft));w.addDocument(doc);- try {+ IllegalStateException expected = expectThrows(IllegalStateException.class, () -> {w.commit();- } catch (IllegalStateException ise) {- assertEquals("ranges can only be indexed with IndexOptions.DOCS (field: foo)", ise.getMessage());- }+ });+ assertEquals("ranges can only be indexed with IndexOptions.DOCS (field: foo)", expected.getMessage());+w.close();dir.close();}@@ -688,11 +687,11 @@ public class TestAutoPrefixTerms extends LuceneTestCase {Document doc = new Document();doc.add(new Field("foo", "bar bar", ft));w.addDocument(doc);- try {+ IllegalStateException expected = expectThrows(IllegalStateException.class, () -> {w.commit();- } catch (IllegalStateException ise) {- assertEquals("ranges can only be indexed with IndexOptions.DOCS (field: foo)", ise.getMessage());- }+ });+ assertEquals("ranges can only be indexed with IndexOptions.DOCS (field: foo)", expected.getMessage());+w.close();dir.close();}diff --git a/lucene/core/src/test/org/apache/lucene/analysis/TestCachingTokenFilter.java b/lucene/core/src/test/org/apache/lucene/analysis/TestCachingTokenFilter.javaindex db3f8e0682c..39248ee2bdc 100644--- a/lucene/core/src/test/org/apache/lucene/analysis/TestCachingTokenFilter.java+++ b/lucene/core/src/test/org/apache/lucene/analysis/TestCachingTokenFilter.java@@ -121,12 +121,10 @@ public class TestCachingTokenFilter extends BaseTokenStreamTestCase {final TokenStream input = analyzer.tokenStream("field", "abc");CachingTokenFilter buffer = new CachingTokenFilter(input);buffer.reset();//ok- try {+ IllegalStateException e = expectThrows(IllegalStateException.class, () -> {buffer.reset();//bad (this used to work which we don't want)- fail("didn't get expected exception");- } catch (IllegalStateException e) {- assertEquals("double reset()", e.getMessage());- }+ });+ assertEquals("double reset()", e.getMessage());}private void checkTokens(TokenStream stream) throws IOException {diff --git a/lucene/core/src/test/org/apache/lucene/analysis/TestNumericTokenStream.java b/lucene/core/src/test/org/apache/lucene/analysis/TestNumericTokenStream.javaindex 837b38abb46..dfaa20e5a2e 100644--- a/lucene/core/src/test/org/apache/lucene/analysis/TestNumericTokenStream.java+++ b/lucene/core/src/test/org/apache/lucene/analysis/TestNumericTokenStream.java@@ -81,19 +81,13 @@ public class TestNumericTokenStream extends BaseTokenStreamTestCase {public void testNotInitialized() throws Exception {final LegacyNumericTokenStream stream=new LegacyNumericTokenStream();- try {+ expectThrows(IllegalStateException.class, () -> {stream.reset();- fail("reset() should not succeed.");- } catch (IllegalStateException e) {- // pass- }+ });- try {+ expectThrows(IllegalStateException.class, () -> {stream.incrementToken();- fail("incrementToken() should not succeed.");- } catch (IllegalStateException e) {- // pass- }+ });stream.close();}@@ -103,18 +97,15 @@ public class TestNumericTokenStream extends BaseTokenStreamTestCase {public void testCTA() throws Exception {final LegacyNumericTokenStream stream=new LegacyNumericTokenStream();- try {+ IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> {stream.addAttribute(CharTermAttribute.class);- fail("Succeeded to add CharTermAttribute.");- } catch (IllegalArgumentException iae) {- assertTrue(iae.getMessage().startsWith("LegacyNumericTokenStream does not support"));- }- try {+ });+ assertTrue(e.getMessage().startsWith("LegacyNumericTokenStream does not support"));++ e = expectThrows(IllegalArgumentException.class, () -> {stream.addAttribute(TestAttribute.class);- fail("Succeeded to add TestAttribute.");- } catch (IllegalArgumentException iae) {- assertTrue(iae.getMessage().startsWith("LegacyNumericTokenStream does not support"));- }+ });+ assertTrue(e.getMessage().startsWith("LegacyNumericTokenStream does not support"));stream.close();}diff --git a/lucene/core/src/test/org/apache/lucene/analysis/tokenattributes/TestCharTermAttributeImpl.java b/lucene/core/src/test/org/apache/lucene/analysis/tokenattributes/TestCharTermAttributeImpl.javaindex e02dd022efa..81dd576be08 100644--- a/lucene/core/src/test/org/apache/lucene/analysis/tokenattributes/TestCharTermAttributeImpl.java+++ b/lucene/core/src/test/org/apache/lucene/analysis/tokenattributes/TestCharTermAttributeImpl.java@@ -191,17 +191,13 @@ public class TestCharTermAttributeImpl extends LuceneTestCase {t.append((CharSequence) t2, 1, 2);assertEquals("4teste", t.toString());- try {+ expectThrows(IndexOutOfBoundsException.class, () -> {t.append((CharSequence) t2, 1, 5);- fail("Should throw IndexOutOfBoundsException");- } catch(IndexOutOfBoundsException iobe) {- }-- try {+ });++ expectThrows(IndexOutOfBoundsException.class, () -> {t.append((CharSequence) t2, 1, 0);- fail("Should throw IndexOutOfBoundsException");- } catch(IndexOutOfBoundsException iobe) {- }+ });t.append((CharSequence) null);assertEquals("4testenull", t.toString());@@ -259,29 +255,21 @@ public class TestCharTermAttributeImpl extends LuceneTestCase {t.append("test");assertEquals("test", t.toString());- try {+ expectThrows(IndexOutOfBoundsException.class, () -> {t.charAt(-1);- fail("Should throw IndexOutOfBoundsException");- } catch(IndexOutOfBoundsException iobe) {- }+ });- try {+ expectThrows(IndexOutOfBoundsException.class, () -> {t.charAt(4);- fail("Should throw IndexOutOfBoundsException");- } catch(IndexOutOfBoundsException iobe) {- }+ });- try {+ expectThrows(IndexOutOfBoundsException.class, () -> {t.subSequence(0, 5);- fail("Should throw IndexOutOfBoundsException");- } catch(IndexOutOfBoundsException iobe) {- }+ });- try {+ expectThrows(IndexOutOfBoundsException.class, () -> {t.subSequence(5, 0);- fail("Should throw IndexOutOfBoundsException");- } catch(IndexOutOfBoundsException iobe) {- }+ });}public static <T extends AttributeImpl> T assertCloneIsEqual(T att) {diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat.javaindex 6acd05332ba..1a2ab627c72 100644--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat.java+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat.java@@ -66,12 +66,9 @@ public class TestBlockPostingsFormat extends BasePostingsFormatTestCase {}private void shouldFail(int minItemsInBlock, int maxItemsInBlock) {- try {+ expectThrows(IllegalArgumentException.class, () -> {new Lucene50PostingsFormat(minItemsInBlock, maxItemsInBlock);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });}public void testInvalidBlockSizes() throws Exception {diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestLucene50StoredFieldsFormatHighCompression.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestLucene50StoredFieldsFormatHighCompression.javaindex 1fe84aa9893..59e48144d44 100644--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestLucene50StoredFieldsFormatHighCompression.java+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestLucene50StoredFieldsFormatHighCompression.java@@ -70,18 +70,12 @@ public class TestLucene50StoredFieldsFormatHighCompression extends BaseStoredFie}public void testInvalidOptions() throws Exception {- try {+ expectThrows(NullPointerException.class, () -> {new Lucene60Codec(null);- fail("didn't hit exception");- } catch (NullPointerException expected) {- // expected- }+ });- try {+ expectThrows(NullPointerException.class, () -> {new Lucene50StoredFieldsFormat(null);- fail("didn't hit exception");- } catch (NullPointerException expected) {- // expected- }+ });}}diff --git a/lucene/core/src/test/org/apache/lucene/document/TestDateTools.java b/lucene/core/src/test/org/apache/lucene/document/TestDateTools.javaindex ed99ff06ee5..fc1aaafb838 100644--- a/lucene/core/src/test/org/apache/lucene/document/TestDateTools.java+++ b/lucene/core/src/test/org/apache/lucene/document/TestDateTools.java@@ -35,19 +35,17 @@ public class TestDateTools extends LuceneTestCase {d = DateTools.stringToDate("20040705091055990");assertEquals("2004-07-05 09:10:55:990", isoFormat(d));- try {- d = DateTools.stringToDate("97"); // no date- fail();- } catch(ParseException e) { /* expected exception */ }- try {- d = DateTools.stringToDate("200401011235009999"); // no date- fail();- } catch(ParseException e) { /* expected exception */ }- try {- d = DateTools.stringToDate("aaaa"); // no date- fail();- } catch(ParseException e) { /* expected exception */ }+ expectThrows(ParseException.class, () -> {+ DateTools.stringToDate("97"); // no date+ });++ expectThrows(ParseException.class, () -> {+ DateTools.stringToDate("200401011235009999"); // no date+ });+ expectThrows(ParseException.class, () -> {+ DateTools.stringToDate("aaaa"); // no date+ });}public void testStringtoTime() throws ParseException {diff --git a/lucene/core/src/test/org/apache/lucene/document/TestDocument.java b/lucene/core/src/test/org/apache/lucene/document/TestDocument.javaindex 41e1f6225be..bd873ec8a9c 100644--- a/lucene/core/src/test/org/apache/lucene/document/TestDocument.java+++ b/lucene/core/src/test/org/apache/lucene/document/TestDocument.java@@ -135,12 +135,9 @@ public class TestDocument extends LuceneTestCase {ft.setStored(true);new Field("name", "value", ft); // okaynew StringField("name", "value", Field.Store.NO); // okay- try {+ expectThrows(IllegalArgumentException.class, () -> {new Field("name", "value", new FieldType());- fail();- } catch (IllegalArgumentException e) {- // expected exception- }+ });Directory dir = newDirectory();RandomIndexWriter w = new RandomIndexWriter(random(), dir);@@ -150,12 +147,9 @@ public class TestDocument extends LuceneTestCase {ft2.setStored(true);ft2.setStoreTermVectors(true);doc.add(new Field("name", "value", ft2));- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);- fail();- } catch (IllegalArgumentException e) {- // expected exception- }+ });w.close();dir.close();}@@ -167,25 +161,18 @@ public class TestDocument extends LuceneTestCase {assertEquals(0, doc.getFields().size());}+ /** test that Document.getFields() actually returns an immutable list */public void testGetFieldsImmutable() {Document doc = makeDocumentWithFields();assertEquals(10, doc.getFields().size());List<IndexableField> fields = doc.getFields();- try {- fields.add( new StringField("name", "value", Field.Store.NO) );- fail("Document.getFields() should return immutable List");- }- catch (UnsupportedOperationException e) {- // OK- }+ expectThrows(UnsupportedOperationException.class, () -> {+ fields.add(new StringField("name", "value", Field.Store.NO));+ });- try {+ expectThrows(UnsupportedOperationException.class, () -> {fields.clear();- fail("Document.getFields() should return immutable List");- }- catch (UnsupportedOperationException e) {- // OK- }+ });}/**@@ -344,14 +331,11 @@ public class TestDocument extends LuceneTestCase {// LUCENE-3616public void testInvalidFields() {- try {+ expectThrows(IllegalArgumentException.class, () -> {Tokenizer tok = new MockTokenizer();tok.setReader(new StringReader(""));new Field("foo", tok, StringField.TYPE_STORED);- fail("did not hit expected exc");- } catch (IllegalArgumentException iae) {- // expected- }+ });}public void testNumericFieldAsString() throws Exception {diff --git a/lucene/core/src/test/org/apache/lucene/document/TestField.java b/lucene/core/src/test/org/apache/lucene/document/TestField.javaindex 85336bc966e..3ac79900b56 100644--- a/lucene/core/src/test/org/apache/lucene/document/TestField.java+++ b/lucene/core/src/test/org/apache/lucene/document/TestField.java@@ -439,111 +439,75 @@ public class TestField extends LuceneTestCase {}private void trySetByteValue(Field f) {- try {+ expectThrows(IllegalArgumentException.class, () -> {f.setByteValue((byte) 10);- fail();- } catch (IllegalArgumentException expected) {- // expected- }+ });}private void trySetBytesValue(Field f) {- try {+ expectThrows(IllegalArgumentException.class, () -> {f.setBytesValue(new byte[] { 5, 5 });- fail();- } catch (IllegalArgumentException expected) {- // expected- }+ });}private void trySetBytesRefValue(Field f) {- try {+ expectThrows(IllegalArgumentException.class, () -> {f.setBytesValue(new BytesRef("bogus"));- fail();- } catch (IllegalArgumentException expected) {- // expected- }+ });}private void trySetDoubleValue(Field f) {- try {+ expectThrows(IllegalArgumentException.class, () -> {f.setDoubleValue(Double.MAX_VALUE);- fail();- } catch (IllegalArgumentException expected) {- // expected- }+ });}private void trySetIntValue(Field f) {- try {+ expectThrows(IllegalArgumentException.class, () -> {f.setIntValue(Integer.MAX_VALUE);- fail();- } catch (IllegalArgumentException expected) {- // expected- }+ });}private void trySetLongValue(Field f) {- try {+ expectThrows(IllegalArgumentException.class, () -> {f.setLongValue(Long.MAX_VALUE);- fail();- } catch (IllegalArgumentException expected) {- // expected- }+ });}private void trySetFloatValue(Field f) {- try {+ expectThrows(IllegalArgumentException.class, () -> {f.setFloatValue(Float.MAX_VALUE);- fail();- } catch (IllegalArgumentException expected) {- // expected- }+ });}private void trySetReaderValue(Field f) {- try {+ expectThrows(IllegalArgumentException.class, () -> {f.setReaderValue(new StringReader("BOO!"));- fail();- } catch (IllegalArgumentException expected) {- // expected- }+ });}private void trySetShortValue(Field f) {- try {+ expectThrows(IllegalArgumentException.class, () -> {f.setShortValue(Short.MAX_VALUE);- fail();- } catch (IllegalArgumentException expected) {- // expected- }+ });}private void trySetStringValue(Field f) {- try {+ expectThrows(IllegalArgumentException.class, () -> {f.setStringValue("BOO!");- fail();- } catch (IllegalArgumentException expected) {- // expected- }+ });}private void trySetTokenStreamValue(Field f) {- try {+ expectThrows(IllegalArgumentException.class, () -> {f.setTokenStream(new CannedTokenStream(new Token("foo", 0, 3)));- fail();- } catch (IllegalArgumentException expected) {- // expected- }+ });}private void trySetBoost(Field f) {- try {+ expectThrows(IllegalArgumentException.class, () -> {f.setBoost(5.0f);- fail();- } catch (IllegalArgumentException expected) {- // expected- }+ });}}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestAddIndexes.java b/lucene/core/src/test/org/apache/lucene/index/TestAddIndexes.javaindex 2a2bfd29569..d1148ef13a6 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestAddIndexes.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestAddIndexes.java@@ -305,16 +305,13 @@ public class TestAddIndexes extends LuceneTestCase {addDocs(writer, 100);writer.close();- writer = newWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND));- try {- // cannot add self- writer.addIndexes(aux, dir);- assertTrue(false);- }- catch (IllegalArgumentException e) {- assertEquals(100, writer.maxDoc());- }- writer.close();+ // cannot add self+ IndexWriter writer2 = newWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND));+ expectThrows(IllegalArgumentException.class, () -> {+ writer2.addIndexes(aux, dir);+ });+ assertEquals(100, writer2.maxDoc());+ writer2.close();// make sure the index is correctverifyNumDocs(dir, 100);@@ -1167,12 +1164,9 @@ public class TestAddIndexes extends LuceneTestCase {IndexWriterConfig conf = newIndexWriterConfig(new MockAnalyzer(random()));conf.setCodec(TestUtil.alwaysPostingsFormat(new MemoryPostingsFormat()));IndexWriter w = new IndexWriter(dir, conf);- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addIndexes(toAdd);- fail("no such codec");- } catch (IllegalArgumentException ex) {- // expected- }+ });w.close();IndexReader open = DirectoryReader.open(dir);assertEquals(0, open.numDocs());@@ -1180,12 +1174,9 @@ public class TestAddIndexes extends LuceneTestCase {dir.close();}- try {+ expectThrows(IllegalArgumentException.class, () -> {DirectoryReader.open(toAdd);- fail("no such codec");- } catch (IllegalArgumentException ex) {- // expected- }+ });toAdd.close();}@@ -1282,12 +1273,9 @@ public class TestAddIndexes extends LuceneTestCase {IndexWriterConfig iwc = newIndexWriterConfig(new MockAnalyzer(random()));RandomIndexWriter w2 = new RandomIndexWriter(random(), dest, iwc);- try {+ expectThrows(LockObtainFailedException.class, () -> {w2.addIndexes(src);- fail("did not hit expected exception");- } catch (LockObtainFailedException lofe) {- // expected- }+ });w1.close();w2.close();diff --git a/lucene/core/src/test/org/apache/lucene/index/TestBinaryDocValuesUpdates.java b/lucene/core/src/test/org/apache/lucene/index/TestBinaryDocValuesUpdates.javaindex a8d38701eb3..4025f58bcbc 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestBinaryDocValuesUpdates.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestBinaryDocValuesUpdates.java@@ -431,19 +431,13 @@ public class TestBinaryDocValuesUpdates extends LuceneTestCase {writer.commit();writer.addDocument(doc); // in-memory document- try {+ expectThrows(IllegalArgumentException.class, () -> {writer.updateBinaryDocValue(new Term("key", "doc"), "bdv", toBytes(17L));- fail("should not have allowed creating new fields through update");- } catch (IllegalArgumentException e) {- // ok- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {writer.updateBinaryDocValue(new Term("key", "doc"), "foo", toBytes(17L));- fail("should not have allowed updating an existing field to binary-dv");- } catch (IllegalArgumentException e) {- // ok- }+ });writer.close();dir.close();diff --git a/lucene/core/src/test/org/apache/lucene/index/TestCodecUtil.java b/lucene/core/src/test/org/apache/lucene/index/TestCodecUtil.javaindex 79fbdeb3fff..9752ce3e752 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestCodecUtil.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestCodecUtil.java@@ -54,23 +54,17 @@ public class TestCodecUtil extends LuceneTestCase {}RAMFile file = new RAMFile();IndexOutput output = new RAMOutputStream(file, true);- try {+ expectThrows(IllegalArgumentException.class, () -> {CodecUtil.writeHeader(output, tooLong.toString(), 5);- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- // expected- }+ });}public void testWriteNonAsciiHeader() throws Exception {RAMFile file = new RAMFile();IndexOutput output = new RAMOutputStream(file, true);- try {+ expectThrows(IllegalArgumentException.class, () -> {CodecUtil.writeHeader(output, "\u1234", 5);- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- // expected- }+ });}public void testReadHeaderWrongMagic() throws Exception {@@ -80,12 +74,9 @@ public class TestCodecUtil extends LuceneTestCase {output.close();IndexInput input = new RAMInputStream("file", file);- try {+ expectThrows(CorruptIndexException.class, () -> {CodecUtil.checkHeader(input, "bogus", 1, 1);- fail("didn't get expected exception");- } catch (CorruptIndexException expected) {- // expected- }+ });}public void testChecksumEntireFile() throws Exception {@@ -111,15 +102,13 @@ public class TestCodecUtil extends LuceneTestCase {ChecksumIndexInput input = new BufferedChecksumIndexInput(new RAMInputStream("file", file));Exception mine = new RuntimeException("fake exception");- try {+ RuntimeException expected = expectThrows(RuntimeException.class, () -> {CodecUtil.checkFooter(input, mine);- fail("didn't get expected exception");- } catch (RuntimeException expected) {- assertEquals("fake exception", expected.getMessage());- Throwable suppressed[] = expected.getSuppressed();- assertEquals(1, suppressed.length);- assertTrue(suppressed[0].getMessage().contains("checksum passed"));- }+ });+ assertEquals("fake exception", expected.getMessage());+ Throwable suppressed[] = expected.getSuppressed();+ assertEquals(1, suppressed.length);+ assertTrue(suppressed[0].getMessage().contains("checksum passed"));input.close();}@@ -135,15 +124,13 @@ public class TestCodecUtil extends LuceneTestCase {CodecUtil.checkHeader(input, "FooBar", 5, 5);assertEquals("this is the data", input.readString());Exception mine = new RuntimeException("fake exception");- try {+ RuntimeException expected = expectThrows(RuntimeException.class, () -> {CodecUtil.checkFooter(input, mine);- fail("didn't get expected exception");- } catch (RuntimeException expected) {- assertEquals("fake exception", expected.getMessage());- Throwable suppressed[] = expected.getSuppressed();- assertEquals(1, suppressed.length);- assertTrue(suppressed[0].getMessage().contains("checksum passed"));- }+ });+ assertEquals("fake exception", expected.getMessage());+ Throwable suppressed[] = expected.getSuppressed();+ assertEquals(1, suppressed.length);+ assertTrue(suppressed[0].getMessage().contains("checksum passed"));input.close();}@@ -161,15 +148,13 @@ public class TestCodecUtil extends LuceneTestCase {// bogusly read a byte too far (can happen)input.readByte();Exception mine = new RuntimeException("fake exception");- try {+ RuntimeException expected = expectThrows(RuntimeException.class, () -> {CodecUtil.checkFooter(input, mine);- fail("didn't get expected exception");- } catch (RuntimeException expected) {- assertEquals("fake exception", expected.getMessage());- Throwable suppressed[] = expected.getSuppressed();- assertEquals(1, suppressed.length);- assertTrue(suppressed[0].getMessage().contains("checksum status indeterminate"));- }+ });+ assertEquals("fake exception", expected.getMessage());+ Throwable suppressed[] = expected.getSuppressed();+ assertEquals(1, suppressed.length);+ assertTrue(suppressed[0].getMessage().contains("checksum status indeterminate"));input.close();}@@ -187,15 +172,13 @@ public class TestCodecUtil extends LuceneTestCase {CodecUtil.checkHeader(input, "FooBar", 5, 5);assertEquals("this is the data", input.readString());Exception mine = new RuntimeException("fake exception");- try {+ RuntimeException expected = expectThrows(RuntimeException.class, () -> {CodecUtil.checkFooter(input, mine);- fail("didn't get expected exception");- } catch (RuntimeException expected) {- assertEquals("fake exception", expected.getMessage());- Throwable suppressed[] = expected.getSuppressed();- assertEquals(1, suppressed.length);- assertTrue(suppressed[0].getMessage().contains("checksum failed"));- }+ });+ assertEquals("fake exception", expected.getMessage());+ Throwable suppressed[] = expected.getSuppressed();+ assertEquals(1, suppressed.length);+ assertTrue(suppressed[0].getMessage().contains("checksum failed"));input.close();}@@ -219,12 +202,9 @@ public class TestCodecUtil extends LuceneTestCase {}RAMFile file = new RAMFile();IndexOutput output = new RAMOutputStream(file, true);- try {+ expectThrows(IllegalArgumentException.class, () -> {CodecUtil.writeIndexHeader(output, "foobar", 5, StringHelper.randomId(), tooLong.toString());- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- // expected- }+ });}public void testWriteVeryLongSuffix() throws Exception {@@ -248,12 +228,9 @@ public class TestCodecUtil extends LuceneTestCase {public void testWriteNonAsciiSuffix() throws Exception {RAMFile file = new RAMFile();IndexOutput output = new RAMOutputStream(file, true);- try {+ expectThrows(IllegalArgumentException.class, () -> {CodecUtil.writeIndexHeader(output, "foobar", 5, StringHelper.randomId(), "\u1234");- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- // expected- }+ });}public void testReadBogusCRC() throws Exception {@@ -267,12 +244,9 @@ public class TestCodecUtil extends LuceneTestCase {IndexInput input = new RAMInputStream("file", file);// read 3 bogus valuesfor (int i = 0; i < 3; i++) {- try {+ expectThrows(CorruptIndexException.class, () -> {CodecUtil.readCRC(input);- fail("didn't get expected exception");- } catch (CorruptIndexException expected) {- // expected- }+ });}// good valueCodecUtil.readCRC(input);@@ -311,28 +285,19 @@ public class TestCodecUtil extends LuceneTestCase {};fakeChecksum.set(-1L); // bad- try {+ expectThrows(IllegalStateException.class, () -> {CodecUtil.writeCRC(fakeOutput);- fail("didn't get expected exception");- } catch (IllegalStateException expected) {- // expected exception- }+ });fakeChecksum.set(1L << 32); // bad- try {+ expectThrows(IllegalStateException.class, () -> {CodecUtil.writeCRC(fakeOutput);- fail("didn't get expected exception");- } catch (IllegalStateException expected) {- // expected exception- }+ });fakeChecksum.set(-(1L << 32)); // bad- try {+ expectThrows(IllegalStateException.class, () -> {CodecUtil.writeCRC(fakeOutput);- fail("didn't get expected exception");- } catch (IllegalStateException expected) {- // expected exception- }+ });fakeChecksum.set((1L << 32) - 1); // okCodecUtil.writeCRC(fakeOutput);diff --git a/lucene/core/src/test/org/apache/lucene/index/TestConcurrentMergeScheduler.java b/lucene/core/src/test/org/apache/lucene/index/TestConcurrentMergeScheduler.javaindex 4c1badaf731..5e885e32c61 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestConcurrentMergeScheduler.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestConcurrentMergeScheduler.java@@ -395,18 +395,12 @@ public class TestConcurrentMergeScheduler extends LuceneTestCase {public void testInvalidMaxMergeCountAndThreads() throws Exception {ConcurrentMergeScheduler cms = new ConcurrentMergeScheduler();- try {+ expectThrows(IllegalArgumentException.class, () -> {cms.setMaxMergesAndThreads(ConcurrentMergeScheduler.AUTO_DETECT_MERGES_AND_THREADS, 3);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // good- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {cms.setMaxMergesAndThreads(3, ConcurrentMergeScheduler.AUTO_DETECT_MERGES_AND_THREADS);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // good- }+ });}public void testLiveMaxMergeCount() throws Exception {@@ -605,19 +599,13 @@ public class TestConcurrentMergeScheduler extends LuceneTestCase {assertEquals(4, cms.getMaxMergeCount());assertEquals(3, cms.getMaxThreadCount());- try {+ expectThrows(IllegalArgumentException.class, () -> {cms.setMaxMergesAndThreads(ConcurrentMergeScheduler.AUTO_DETECT_MERGES_AND_THREADS, 4);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {cms.setMaxMergesAndThreads(4, ConcurrentMergeScheduler.AUTO_DETECT_MERGES_AND_THREADS);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });cms.setMaxMergesAndThreads(ConcurrentMergeScheduler.AUTO_DETECT_MERGES_AND_THREADS, ConcurrentMergeScheduler.AUTO_DETECT_MERGES_AND_THREADS);assertEquals(ConcurrentMergeScheduler.AUTO_DETECT_MERGES_AND_THREADS, cms.getMaxMergeCount());diff --git a/lucene/core/src/test/org/apache/lucene/index/TestCrashCausesCorruptIndex.java b/lucene/core/src/test/org/apache/lucene/index/TestCrashCausesCorruptIndex.javaindex aebfb50e175..9fd20aba509 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestCrashCausesCorruptIndex.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestCrashCausesCorruptIndex.java@@ -72,13 +72,11 @@ public class TestCrashCausesCorruptIndex extends LuceneTestCase {crashAfterCreateOutput.setCrashAfterCreateOutput("pending_segments_2");indexWriter.addDocument(getDocument());- try {- // tries to write segments_2 but hits fake exc:+ // tries to write segments_2 but hits fake exc:+ expectThrows(CrashingException.class, () -> {indexWriter.commit();- fail("should have hit CrashingException");- } catch (CrashingException e) {- // expected- }+ });+// writes segments_3indexWriter.close();assertFalse(slowFileExists(realDirectory, "segments_2"));diff --git a/lucene/core/src/test/org/apache/lucene/index/TestDirectoryReader.java b/lucene/core/src/test/org/apache/lucene/index/TestDirectoryReader.javaindex f65b079e033..24b2c5095e5 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestDirectoryReader.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestDirectoryReader.java@@ -718,12 +718,9 @@ public class TestDirectoryReader extends LuceneTestCase {public void testNoDir() throws Throwable {Path tempDir = createTempDir("doesnotexist");Directory dir = newFSDirectory(tempDir);- try {+ expectThrows(IndexNotFoundException.class, () -> {DirectoryReader.open(dir);- fail("did not hit expected exception");- } catch (IndexNotFoundException nsde) {- // expected- }+ });dir.close();}@@ -955,12 +952,9 @@ public class TestDirectoryReader extends LuceneTestCase {DirectoryReader r = writer.getReader();writer.close();r.document(0);- try {+ expectThrows(IllegalArgumentException.class, () -> {r.document(1);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });r.close();dir.close();}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestDirectoryReaderReopen.java b/lucene/core/src/test/org/apache/lucene/index/TestDirectoryReaderReopen.javaindex 189ef203be7..6afa091cf01 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestDirectoryReaderReopen.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestDirectoryReaderReopen.java@@ -672,13 +672,9 @@ public class TestDirectoryReaderReopen extends LuceneTestCase {// Now reopen://System.out.println("TEST: now reopen");- try {- IndexReader r2 = DirectoryReader.openIfChanged(r);- //System.out.println("got " + r2);- fail("didn't hit exception");- } catch (FakeIOException fio) {- // expected- }+ expectThrows(FakeIOException.class, () -> {+ DirectoryReader.openIfChanged(r);+ });IndexSearcher s = newSearcher(r);assertEquals(1, s.search(new TermQuery(new Term("id", "id")), 1).totalHits);@@ -726,12 +722,9 @@ public class TestDirectoryReaderReopen extends LuceneTestCase {w.commit();w.close();- try {+ expectThrows(IllegalStateException.class, () -> {DirectoryReader.openIfChanged(r);- fail("didn't hit expected exception");- } catch (IllegalStateException ise) {- // expected- }+ });r.close();w.close();@@ -772,12 +765,9 @@ public class TestDirectoryReaderReopen extends LuceneTestCase {w.commit();w.close();- try {+ expectThrows(IllegalStateException.class, () -> {DirectoryReader.openIfChanged(r);- fail("didn't hit expected exception");- } catch (IllegalStateException ise) {- // expected- }+ });r.close();dir.close();diff --git a/lucene/core/src/test/org/apache/lucene/index/TestDocInverterPerFieldErrorInfo.java b/lucene/core/src/test/org/apache/lucene/index/TestDocInverterPerFieldErrorInfo.javaindex 1e934789a12..17e0f2ed297 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestDocInverterPerFieldErrorInfo.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestDocInverterPerFieldErrorInfo.java@@ -76,14 +76,12 @@ public class TestDocInverterPerFieldErrorInfo extends LuceneTestCase {writer = new IndexWriter(dir, c);Document doc = new Document();doc.add(newField("distinctiveFieldName", "aaa ", storedTextType));- try {+ expectThrows(BadNews.class, () -> {writer.addDocument(doc);- fail("Failed to fail.");- } catch(BadNews badNews) {- infoPrintStream.flush();- String infoStream = new String(infoBytes.toByteArray(), IOUtils.UTF_8);- assertTrue(infoStream.contains("distinctiveFieldName"));- }+ });+ infoPrintStream.flush();+ String infoStream = new String(infoBytes.toByteArray(), IOUtils.UTF_8);+ assertTrue(infoStream.contains("distinctiveFieldName"));writer.close();dir.close();diff --git a/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java b/lucene/core/src/test/org/apache/lucene/index/TestDocValues.javaindex b8573cb61d6..ad4d60cad9d 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestDocValues.java@@ -69,30 +69,24 @@ public class TestDocValues extends LuceneTestCase {LeafReader r = getOnlySegmentReader(dr);// errors- try {+ expectThrows(IllegalStateException.class, () -> {DocValues.getBinary(r, "foo");- fail();- } catch (IllegalStateException expected) {}- try {+ });+ expectThrows(IllegalStateException.class, () -> {DocValues.getNumeric(r, "foo");- fail();- } catch (IllegalStateException expected) {}- try {+ });+ expectThrows(IllegalStateException.class, () -> {DocValues.getSorted(r, "foo");- fail();- } catch (IllegalStateException expected) {}- try {+ });+ expectThrows(IllegalStateException.class, () -> {DocValues.getSortedSet(r, "foo");- fail();- } catch (IllegalStateException expected) {}- try {+ });+ expectThrows(IllegalStateException.class, () -> {DocValues.getSortedNumeric(r, "foo");- fail();- } catch (IllegalStateException expected) {}- try {+ });+ expectThrows(IllegalStateException.class, () -> {DocValues.getDocsWithField(r, "foo");- fail();- } catch (IllegalStateException expected) {}+ });dr.close();iw.close();@@ -117,18 +111,15 @@ public class TestDocValues extends LuceneTestCase {assertNotNull(DocValues.getDocsWithField(r, "foo"));// errors- try {+ expectThrows(IllegalStateException.class, () -> {DocValues.getBinary(r, "foo");- fail();- } catch (IllegalStateException expected) {}- try {+ });+ expectThrows(IllegalStateException.class, () -> {DocValues.getSorted(r, "foo");- fail();- } catch (IllegalStateException expected) {}- try {+ });+ expectThrows(IllegalStateException.class, () -> {DocValues.getSortedSet(r, "foo");- fail();- } catch (IllegalStateException expected) {}+ });dr.close();iw.close();@@ -152,22 +143,18 @@ public class TestDocValues extends LuceneTestCase {assertNotNull(DocValues.getDocsWithField(r, "foo"));// errors- try {+ expectThrows(IllegalStateException.class, () -> {DocValues.getNumeric(r, "foo");- fail();- } catch (IllegalStateException expected) {}- try {+ });+ expectThrows(IllegalStateException.class, () -> {DocValues.getSorted(r, "foo");- fail();- } catch (IllegalStateException expected) {}- try {+ });+ expectThrows(IllegalStateException.class, () -> {DocValues.getSortedSet(r, "foo");- fail();- } catch (IllegalStateException expected) {}- try {+ });+ expectThrows(IllegalStateException.class, () -> {DocValues.getSortedNumeric(r, "foo");- fail();- } catch (IllegalStateException expected) {}+ });dr.close();iw.close();@@ -193,14 +180,12 @@ public class TestDocValues extends LuceneTestCase {assertNotNull(DocValues.getDocsWithField(r, "foo"));// errors- try {+ expectThrows(IllegalStateException.class, () -> {DocValues.getNumeric(r, "foo");- fail();- } catch (IllegalStateException expected) {}- try {+ });+ expectThrows(IllegalStateException.class, () -> {DocValues.getSortedNumeric(r, "foo");- fail();- } catch (IllegalStateException expected) {}+ });dr.close();iw.close();@@ -224,22 +209,18 @@ public class TestDocValues extends LuceneTestCase {assertNotNull(DocValues.getDocsWithField(r, "foo"));// errors- try {+ expectThrows(IllegalStateException.class, () -> {DocValues.getBinary(r, "foo");- fail();- } catch (IllegalStateException expected) {}- try {+ });+ expectThrows(IllegalStateException.class, () -> {DocValues.getNumeric(r, "foo");- fail();- } catch (IllegalStateException expected) {}- try {+ });+ expectThrows(IllegalStateException.class, () -> {DocValues.getSorted(r, "foo");- fail();- } catch (IllegalStateException expected) {}- try {+ });+ expectThrows(IllegalStateException.class, () -> {DocValues.getSortedNumeric(r, "foo");- fail();- } catch (IllegalStateException expected) {}+ });dr.close();iw.close();@@ -263,22 +244,18 @@ public class TestDocValues extends LuceneTestCase {assertNotNull(DocValues.getDocsWithField(r, "foo"));// errors- try {+ expectThrows(IllegalStateException.class, () -> {DocValues.getBinary(r, "foo");- fail();- } catch (IllegalStateException expected) {}- try {+ });+ expectThrows(IllegalStateException.class, () -> {DocValues.getNumeric(r, "foo");- fail();- } catch (IllegalStateException expected) {}- try {+ });+ expectThrows(IllegalStateException.class, () -> {DocValues.getSorted(r, "foo");- fail();- } catch (IllegalStateException expected) {}- try {+ });+ expectThrows(IllegalStateException.class, () -> {DocValues.getSortedSet(r, "foo");- fail();- } catch (IllegalStateException expected) {}+ });dr.close();iw.close();diff --git a/lucene/core/src/test/org/apache/lucene/index/TestDocValuesIndexing.java b/lucene/core/src/test/org/apache/lucene/index/TestDocValuesIndexing.javaindex a20edae872d..44b5b75bbe3 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestDocValuesIndexing.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestDocValuesIndexing.java@@ -102,12 +102,10 @@ public class TestDocValuesIndexing extends LuceneTestCase {// Index doc values are single-valued so we should not// be able to add same field more than once:doc.add(f);- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });DirectoryReader r = w.getReader();w.close();@@ -126,12 +124,9 @@ public class TestDocValuesIndexing extends LuceneTestCase {// Index doc values are single-valued so we should not// be able to add same field more than once:doc.add(new BinaryDocValuesField("field", new BytesRef("blah")));- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);- fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });DirectoryReader r = w.getReader();w.close();@@ -150,12 +145,10 @@ public class TestDocValuesIndexing extends LuceneTestCase {// Index doc values are single-valued so we should not// be able to add same field more than once:doc.add(new SortedDocValuesField("field", new BytesRef("hello")));- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);- fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+DirectoryReader r = w.getReader();assertEquals(17, getOnlySegmentReader(r).getNumericDocValues("field").get(0));r.close();@@ -232,12 +225,10 @@ public class TestDocValuesIndexing extends LuceneTestCase {Document doc = new Document();doc.add(new NumericDocValuesField("foo", 0));doc.add(new SortedDocValuesField("foo", new BytesRef("hello")));- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);- fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+IndexReader ir = w.getReader();assertEquals(1, ir.numDocs());ir.close();@@ -253,14 +244,12 @@ public class TestDocValuesIndexing extends LuceneTestCase {doc.add(new NumericDocValuesField("foo", 0));w.addDocument(doc);- doc = new Document();- doc.add(new SortedDocValuesField("foo", new BytesRef("hello")));- try {- w.addDocument(doc);- fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ Document doc2 = new Document();+ doc2.add(new SortedDocValuesField("foo", new BytesRef("hello")));+ expectThrows(IllegalArgumentException.class, () -> {+ w.addDocument(doc2);+ });+IndexReader ir = w.getReader();assertEquals(1, ir.numDocs());ir.close();@@ -281,16 +270,10 @@ public class TestDocValuesIndexing extends LuceneTestCase {iwriter.addDocument(doc);doc.add(new SortedDocValuesField("dv", new BytesRef("bar!")));- try {+ expectThrows(IllegalArgumentException.class, () -> {iwriter.addDocument(doc);- fail("didn't hit expected exception");- } catch (IllegalArgumentException expected) {- // expected- if (VERBOSE) {- System.out.println("hit exc:");- expected.printStackTrace(System.out);- }- }+ });+IndexReader ir = iwriter.getReader();assertEquals(1, ir.numDocs());ir.close();@@ -311,12 +294,9 @@ public class TestDocValuesIndexing extends LuceneTestCase {iwriter.addDocument(doc);doc.add(new BinaryDocValuesField("dv", new BytesRef("bar!")));- try {+ expectThrows(IllegalArgumentException.class, () -> {iwriter.addDocument(doc);- fail("didn't hit expected exception");- } catch (IllegalArgumentException expected) {- // expected- }+ });IndexReader ir = iwriter.getReader();assertEquals(1, ir.numDocs());@@ -339,12 +319,10 @@ public class TestDocValuesIndexing extends LuceneTestCase {iwriter.addDocument(doc);doc.add(new NumericDocValuesField("dv", 2));- try {+ expectThrows(IllegalArgumentException.class, () -> {iwriter.addDocument(doc);- fail("didn't hit expected exception");- } catch (IllegalArgumentException expected) {- // expected- }+ });+IndexReader ir = iwriter.getReader();assertEquals(1, ir.numDocs());ir.close();@@ -364,17 +342,15 @@ public class TestDocValuesIndexing extends LuceneTestCase {doc.add(new SortedDocValuesField("dv", new BytesRef("just fine")));iwriter.addDocument(doc);- doc = new Document();+ Document hugeDoc = new Document();byte bytes[] = new byte[100000];BytesRef b = new BytesRef(bytes);random().nextBytes(bytes);- doc.add(new SortedDocValuesField("dv", b));- try {- iwriter.addDocument(doc);- fail("did not get expected exception");- } catch (IllegalArgumentException expected) {- // expected- }+ hugeDoc.add(new SortedDocValuesField("dv", b));+ expectThrows(IllegalArgumentException.class, () -> {+ iwriter.addDocument(hugeDoc);+ });+IndexReader ir = iwriter.getReader();assertEquals(1, ir.numDocs());ir.close();@@ -394,17 +370,15 @@ public class TestDocValuesIndexing extends LuceneTestCase {doc.add(new SortedSetDocValuesField("dv", new BytesRef("just fine")));iwriter.addDocument(doc);- doc = new Document();+ Document hugeDoc = new Document();byte bytes[] = new byte[100000];BytesRef b = new BytesRef(bytes);random().nextBytes(bytes);- doc.add(new SortedSetDocValuesField("dv", b));- try {- iwriter.addDocument(doc);- fail("did not get expected exception");- } catch (IllegalArgumentException expected) {- // expected- }+ hugeDoc.add(new SortedSetDocValuesField("dv", b));+ expectThrows(IllegalArgumentException.class, () -> {+ iwriter.addDocument(hugeDoc);+ });+IndexReader ir = iwriter.getReader();assertEquals(1, ir.numDocs());ir.close();@@ -421,14 +395,12 @@ public class TestDocValuesIndexing extends LuceneTestCase {w.addDocument(doc);w.commit();- doc = new Document();- doc.add(new SortedDocValuesField("foo", new BytesRef("hello")));- try {- w.addDocument(doc);- fail("did not get expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ Document doc2 = new Document();+ doc2.add(new SortedDocValuesField("foo", new BytesRef("hello")));+ expectThrows(IllegalArgumentException.class, () -> {+ w.addDocument(doc2);+ });+w.close();dir.close();}@@ -475,16 +447,14 @@ public class TestDocValuesIndexing extends LuceneTestCase {w.addDocument(doc);w.close();- w = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())));- doc = new Document();- doc.add(new SortedDocValuesField("foo", new BytesRef("hello")));- try {- w.addDocument(doc);- fail("did not get expected exception");- } catch (IllegalArgumentException iae) {- // expected- }- w.close();+ IndexWriter w2 = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())));+ Document doc2 = new Document();+ doc2.add(new SortedDocValuesField("foo", new BytesRef("hello")));+ expectThrows(IllegalArgumentException.class, () -> {+ w2.addDocument(doc2);+ });++ w2.close();dir.close();}@@ -496,21 +466,19 @@ public class TestDocValuesIndexing extends LuceneTestCase {w.addDocument(doc);w.close();- doc = new Document();- w = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())));- doc.add(new StringField("foo", "bar", Field.Store.NO));- doc.add(new BinaryDocValuesField("foo", new BytesRef("foo")));- try {- // NOTE: this case follows a different code path inside- // DefaultIndexingChain/FieldInfos, because the field (foo)- // is first added without DocValues:- w.addDocument(doc);- fail("did not get expected exception");- } catch (IllegalArgumentException iae) {- // expected- }- w.forceMerge(1);- w.close();+ Document doc2 = new Document();+ IndexWriter w2 = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())));+ doc2.add(new StringField("foo", "bar", Field.Store.NO));+ doc2.add(new BinaryDocValuesField("foo", new BytesRef("foo")));+ // NOTE: this case follows a different code path inside+ // DefaultIndexingChain/FieldInfos, because the field (foo)+ // is first added without DocValues:+ expectThrows(IllegalArgumentException.class, () -> {+ w2.addDocument(doc2);+ });++ w2.forceMerge(1);+ w2.close();dir.close();}@@ -522,23 +490,21 @@ public class TestDocValuesIndexing extends LuceneTestCase {w.addDocument(doc);w.close();- doc = new Document();- w = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())));- doc.add(new StringField("foo", "bar", Field.Store.NO));- doc.add(new BinaryDocValuesField("foo", new BytesRef("foo")));- try {- // NOTE: this case follows a different code path inside- // DefaultIndexingChain/FieldInfos, because the field (foo)- // is first added without DocValues:- w.addDocument(doc);- fail("did not get expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ Document doc2 = new Document();+ IndexWriter w2 = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())));+ doc2.add(new StringField("foo", "bar", Field.Store.NO));+ doc2.add(new BinaryDocValuesField("foo", new BytesRef("foo")));+ // NOTE: this case follows a different code path inside+ // DefaultIndexingChain/FieldInfos, because the field (foo)+ // is first added without DocValues:+ expectThrows(IllegalArgumentException.class, () -> {+ w2.addDocument(doc2);+ });+// Also add another document so there is a segment to write here:- w.addDocument(new Document());- w.forceMerge(1);- w.close();+ w2.addDocument(new Document());+ w2.forceMerge(1);+ w2.close();dir.close();}@@ -606,20 +572,14 @@ public class TestDocValuesIndexing extends LuceneTestCase {w2.addDocument(doc);w2.close();- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addIndexes(new Directory[] {dir2});- fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });DirectoryReader r = DirectoryReader.open(dir2);- try {+ expectThrows(IllegalArgumentException.class, () -> {TestUtil.addIndexesSlowly(w, r);- fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });r.close();dir2.close();@@ -634,14 +594,12 @@ public class TestDocValuesIndexing extends LuceneTestCase {Document doc = new Document();doc.add(new NumericDocValuesField("dv", 0L));writer.addDocument(doc);- doc = new Document();- doc.add(new SortedDocValuesField("dv", new BytesRef("foo")));- try {- writer.addDocument(doc);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ Document doc2 = new Document();+ doc2.add(new SortedDocValuesField("dv", new BytesRef("foo")));+ expectThrows(IllegalArgumentException.class, () -> {+ writer.addDocument(doc2);+ });+IndexReader ir = writer.getReader();assertEquals(1, ir.numDocs());ir.close();@@ -659,16 +617,14 @@ public class TestDocValuesIndexing extends LuceneTestCase {writer.close();conf = newIndexWriterConfig(new MockAnalyzer(random()));- writer = new IndexWriter(dir, conf);- doc = new Document();- doc.add(new SortedDocValuesField("dv", new BytesRef("foo")));- try {- writer.addDocument(doc);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }- writer.close();+ IndexWriter writer2 = new IndexWriter(dir, conf);+ Document doc2 = new Document();+ doc2.add(new SortedDocValuesField("dv", new BytesRef("foo")));+ expectThrows(IllegalArgumentException.class, () -> {+ writer2.addDocument(doc2);+ });++ writer2.close();dir.close();}@@ -751,17 +707,14 @@ public class TestDocValuesIndexing extends LuceneTestCase {Directory dir2 = newDirectory();conf = newIndexWriterConfig(new MockAnalyzer(random()));- writer = new IndexWriter(dir2, conf);+ IndexWriter writer2 = new IndexWriter(dir2, conf);doc = new Document();doc.add(new SortedDocValuesField("dv", new BytesRef("foo")));- writer.addDocument(doc);- try {- writer.addIndexes(dir);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }- writer.close();+ writer2.addDocument(doc);+ expectThrows(IllegalArgumentException.class, () -> {+ writer2.addIndexes(dir);+ });+ writer2.close();dir.close();dir2.close();@@ -778,19 +731,17 @@ public class TestDocValuesIndexing extends LuceneTestCase {Directory dir2 = newDirectory();conf = newIndexWriterConfig(new MockAnalyzer(random()));- writer = new IndexWriter(dir2, conf);+ IndexWriter writer2 = new IndexWriter(dir2, conf);doc = new Document();doc.add(new SortedDocValuesField("dv", new BytesRef("foo")));- writer.addDocument(doc);+ writer2.addDocument(doc);DirectoryReader reader = DirectoryReader.open(dir);- try {- TestUtil.addIndexesSlowly(writer, reader);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ expectThrows(IllegalArgumentException.class, () -> {+ TestUtil.addIndexesSlowly(writer2, reader);+ });+reader.close();- writer.close();+ writer2.close();dir.close();dir2.close();@@ -807,17 +758,15 @@ public class TestDocValuesIndexing extends LuceneTestCase {Directory dir2 = newDirectory();conf = newIndexWriterConfig(new MockAnalyzer(random()));- writer = new IndexWriter(dir2, conf);- writer.addIndexes(dir);- doc = new Document();- doc.add(new SortedDocValuesField("dv", new BytesRef("foo")));- try {- writer.addDocument(doc);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }- writer.close();+ IndexWriter writer2 = new IndexWriter(dir2, conf);+ writer2.addIndexes(dir);+ Document doc2 = new Document();+ doc2.add(new SortedDocValuesField("dv", new BytesRef("foo")));+ expectThrows(IllegalArgumentException.class, () -> {+ writer2.addDocument(doc2);+ });++ writer2.close();dir2.close();dir.close();}@@ -833,19 +782,17 @@ public class TestDocValuesIndexing extends LuceneTestCase {Directory dir2 = newDirectory();conf = newIndexWriterConfig(new MockAnalyzer(random()));- writer = new IndexWriter(dir2, conf);+ IndexWriter writer2 = new IndexWriter(dir2, conf);DirectoryReader reader = DirectoryReader.open(dir);- TestUtil.addIndexesSlowly(writer, reader);+ TestUtil.addIndexesSlowly(writer2, reader);reader.close();- doc = new Document();- doc.add(new SortedDocValuesField("dv", new BytesRef("foo")));- try {- writer.addDocument(doc);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }- writer.close();+ Document doc2 = new Document();+ doc2.add(new SortedDocValuesField("dv", new BytesRef("foo")));+ expectThrows(IllegalArgumentException.class, () -> {+ writer2.addDocument(doc2);+ });++ writer2.close();dir2.close();dir.close();}@@ -890,14 +837,12 @@ public class TestDocValuesIndexing extends LuceneTestCase {writer.addDocument(doc);writer.commit();- doc = new Document();- doc.add(new BinaryDocValuesField("f", new BytesRef("mock")));- try {- writer.addDocument(doc);- fail("should not have succeeded to add a field with different DV type than what already exists");- } catch (IllegalArgumentException e) {- writer.rollback();- }+ Document doc2 = new Document();+ doc2.add(new BinaryDocValuesField("f", new BytesRef("mock")));+ expectThrows(IllegalArgumentException.class, () -> {+ writer.addDocument(doc2);+ });+ writer.rollback();dir.close();}@@ -919,12 +864,10 @@ public class TestDocValuesIndexing extends LuceneTestCase {}});doc.add(field);- try {+ expectThrows(RuntimeException.class, () -> {w.addDocument(doc);- fail("did not hit exception");- } catch (RuntimeException re) {- // expected- }+ });+w.addDocument(new Document());w.close();dir.close();diff --git a/lucene/core/src/test/org/apache/lucene/index/TestExceedMaxTermLength.java b/lucene/core/src/test/org/apache/lucene/index/TestExceedMaxTermLength.javaindex fb8493af3f6..fc3884ab226 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestExceedMaxTermLength.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestExceedMaxTermLength.java@@ -83,21 +83,19 @@ public class TestExceedMaxTermLength extends LuceneTestCase {}doc.add(f);- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);- fail("Did not get an exception from adding a monster term");- } catch (IllegalArgumentException e) {- final String maxLengthMsg = String.valueOf(IndexWriter.MAX_TERM_LENGTH);- final String msg = e.getMessage();- assertTrue("IllegalArgumentException didn't mention 'immense term': " + msg,- msg.contains("immense term"));- assertTrue("IllegalArgumentException didn't mention max length ("+maxLengthMsg+"): " + msg,- msg.contains(maxLengthMsg));- assertTrue("IllegalArgumentException didn't mention field name ("+name+"): " + msg,- msg.contains(name));- assertTrue("IllegalArgumentException didn't mention original message: " + msg,- msg.contains("bytes can be at most") && msg.contains("in length; got"));- }+ });+ String maxLengthMsg = String.valueOf(IndexWriter.MAX_TERM_LENGTH);+ String msg = expected.getMessage();+ assertTrue("IllegalArgumentException didn't mention 'immense term': " + msg,+ msg.contains("immense term"));+ assertTrue("IllegalArgumentException didn't mention max length ("+maxLengthMsg+"): " + msg,+ msg.contains(maxLengthMsg));+ assertTrue("IllegalArgumentException didn't mention field name ("+name+"): " + msg,+ msg.contains(name));+ assertTrue("IllegalArgumentException didn't mention original message: " + msg,+ msg.contains("bytes can be at most") && msg.contains("in length; got"));} finally {w.close();}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestExitableDirectoryReader.java b/lucene/core/src/test/org/apache/lucene/index/TestExitableDirectoryReader.javaindex 1aa6eea1a77..36c9e0d80a1 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestExitableDirectoryReader.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestExitableDirectoryReader.java@@ -133,16 +133,12 @@ public class TestExitableDirectoryReader extends LuceneTestCase {directoryReader = DirectoryReader.open(directory);exitableDirectoryReader = new ExitableDirectoryReader(directoryReader, new QueryTimeoutImpl(1));reader = new TestReader(exitableDirectoryReader);- searcher = new IndexSearcher(reader);- try {- searcher.search(query, 10);- fail("This query should have led to an ExitingReaderException!");- } catch (ExitingReaderException ex) {- // Do nothing, we expect this!- } finally {- reader.close();- exitableDirectoryReader.close();- }+ IndexSearcher slowSearcher = new IndexSearcher(reader);+ expectThrows(ExitingReaderException.class, () -> {+ slowSearcher.search(query, 10);+ });+ reader.close();+ exitableDirectoryReader.close();// Set maximum time out and expect the query to complete.// Not checking the validity of the result, all we are bothered about in this test is the timing out.diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexInput.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexInput.javaindex 73ba64a6f35..d5e5d92606e 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexInput.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexInput.java@@ -143,22 +143,16 @@ public class TestIndexInput extends LuceneTestCase {assertEquals("\u0000",is.readString());assertEquals("Lu\u0000ce\u0000ne",is.readString());- try {+ Exception expected = expectThrows(expectedEx, () -> {is.readVInt();- fail("Should throw " + expectedEx.getName());- } catch (Exception e) {- assertTrue(e.getMessage().startsWith("Invalid vInt"));- assertTrue(expectedEx.isInstance(e));- }+ });+ assertTrue(expected.getMessage().startsWith("Invalid vInt"));assertEquals(1, is.readVInt()); // guard value- try {+ expected = expectThrows(expectedEx, () -> {is.readVLong();- fail("Should throw " + expectedEx.getName());- } catch (Exception e) {- assertTrue(e.getMessage().startsWith("Invalid vLong"));- assertTrue(expectedEx.isInstance(e));- }+ });+ assertTrue(expected.getMessage().startsWith("Invalid vLong"));assertEquals(1L, is.readVLong()); // guard value}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexReaderClose.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexReaderClose.javaindex b89679cdc7c..6b22fd711e2 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexReaderClose.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexReaderClose.java@@ -68,22 +68,20 @@ public class TestIndexReaderClose extends LuceneTestCase {if (!faultySet && !throwOnClose) {reader.addReaderClosedListener(new FaultyListener());}- try {++ IllegalStateException expected = expectThrows(IllegalStateException.class, () -> {reader.close();- fail("expected Exception");- } catch (IllegalStateException ex) {- if (throwOnClose) {- assertEquals("BOOM!", ex.getMessage());- } else {- assertEquals("GRRRRRRRRRRRR!", ex.getMessage());- }+ });++ if (throwOnClose) {+ assertEquals("BOOM!", expected.getMessage());+ } else {+ assertEquals("GRRRRRRRRRRRR!", expected.getMessage());}- try {+ expectThrows(AlreadyClosedException.class, () -> {reader.fields();- fail("we are closed");- } catch (AlreadyClosedException ex) {- }+ });if (random().nextBoolean()) {reader.close(); // call it againdiff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.javaindex 6e466e58d65..7461618bc55 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java@@ -229,20 +229,16 @@ public class TestIndexWriter extends LuceneTestCase {public void testChangesAfterClose() throws IOException {Directory dir = newDirectory();+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())));- IndexWriter writer = null;-- writer = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())));addDoc(writer);// closewriter.close();- try {+ expectThrows(AlreadyClosedException.class, () -> {addDoc(writer);- fail("did not hit AlreadyClosedException");- } catch (AlreadyClosedException e) {- // expected- }+ });+dir.close();}@@ -801,12 +797,10 @@ public class TestIndexWriter extends LuceneTestCase {IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())));Document doc = new Document();doc.add(new TextField("field", tokens));- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);- fail("did not hit expected exception");- } catch (IllegalArgumentException iea) {- // expected- }+ });+w.close();dir.close();}@@ -1564,21 +1558,18 @@ public class TestIndexWriter extends LuceneTestCase {char[] chars = new char[DocumentsWriterPerThread.MAX_TERM_LENGTH_UTF8];Arrays.fill(chars, 'x');- Document doc = new Document();+ Document hugeDoc = new Document();final String bigTerm = new String(chars);// This contents produces a too-long term:String contents = "abc xyz x" + bigTerm + " another term";- doc.add(new TextField("content", contents, Field.Store.NO));- try {- w.addDocument(doc);- fail("should have hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ hugeDoc.add(new TextField("content", contents, Field.Store.NO));+ expectThrows(IllegalArgumentException.class, () -> {+ w.addDocument(hugeDoc);+ });// Make sure we can add another normal document- doc = new Document();+ Document doc = new Document();doc.add(new TextField("content", "abc bbb ccc", Field.Store.NO));w.addDocument(doc);@@ -1612,22 +1603,22 @@ public class TestIndexWriter extends LuceneTestCase {IndexWriterConfig iwc = newIndexWriterConfig();iwc.setCodec(TestUtil.getDefaultCodec());- w = new RandomIndexWriter(random(), dir, iwc);+ RandomIndexWriter w2 = new RandomIndexWriter(random(), dir, iwc);contentField.setStringValue("other");- w.addDocument(doc);+ w2.addDocument(doc);contentField.setStringValue("term");- w.addDocument(doc);+ w2.addDocument(doc);contentField.setStringValue(bigTerm);- w.addDocument(doc);+ w2.addDocument(doc);contentField.setStringValue("zzz");- w.addDocument(doc);+ w2.addDocument(doc);- reader = w.getReader();- w.close();+ reader = w2.getReader();+ w2.close();assertEquals(1, reader.docFreq(new Term("content", bigTerm)));reader.close();@@ -1689,12 +1680,10 @@ public class TestIndexWriter extends LuceneTestCase {Directory d = newFSDirectory(createTempDir("TestIndexWriter.testWhetherDeleteAllDeletesWriteLock"), SimpleFSLockFactory.INSTANCE);RandomIndexWriter w1 = new RandomIndexWriter(random(), d);w1.deleteAll();- try {+ expectThrows(LockObtainFailedException.class, () -> {new RandomIndexWriter(random(), d, newIndexWriterConfig(null));- fail("should not be able to create another writer");- } catch (LockObtainFailedException lofe) {- // expected- }+ });+w1.close();d.close();}@@ -1742,12 +1731,9 @@ public class TestIndexWriter extends LuceneTestCase {new IndexWriterConfig(new MockAnalyzer(random())));w.prepareCommit();- try {+ expectThrows(IllegalStateException.class, () -> {w.close();- fail("should have hit exception");- } catch (IllegalStateException ise) {- // expected- }+ });w.commit();w.close();IndexReader r = DirectoryReader.open(dir);@@ -1969,19 +1955,21 @@ public class TestIndexWriter extends LuceneTestCase {Directory dir = newDirectory();IndexWriterConfig iwConf = newIndexWriterConfig(null);RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwConf);+// add 3 good docsfor (int i = 0; i < 3; i++) {Document doc = new Document();doc.add(new StringField("id", Integer.toString(i), Field.Store.NO));iw.addDocument(doc);}+// add broken doc- try {+ expectThrows(NullPointerException.class, () -> {Document broke = new Document();broke.add(newTextField("test", "broken", Field.Store.NO));iw.addDocument(broke);- fail();- } catch (NullPointerException expected) {}+ });+// ensure good docs are still okIndexReader ir = iw.getReader();assertEquals(3, ir.numDocs());@@ -1993,20 +1981,23 @@ public class TestIndexWriter extends LuceneTestCase {public void testNullDocument() throws IOException {Directory dir = newDirectory();RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+// add 3 good docsfor (int i = 0; i < 3; i++) {Document doc = new Document();doc.add(new StringField("id", Integer.toString(i), Field.Store.NO));iw.addDocument(doc);}+// add broken doc- try {+ expectThrows(NullPointerException.class, () -> {iw.addDocument(null);- fail();- } catch (NullPointerException expected) {}+ });+// ensure good docs are still okIndexReader ir = iw.getReader();assertEquals(3, ir.numDocs());+ir.close();iw.close();dir.close();@@ -2015,20 +2006,23 @@ public class TestIndexWriter extends LuceneTestCase {public void testNullDocuments() throws IOException {Directory dir = newDirectory();RandomIndexWriter iw = new RandomIndexWriter(random(), dir);+// add 3 good docsfor (int i = 0; i < 3; i++) {Document doc = new Document();doc.add(new StringField("id", Integer.toString(i), Field.Store.NO));iw.addDocument(doc);}+// add broken doc block- try {+ expectThrows(NullPointerException.class, () -> {iw.addDocuments(null);- fail();- } catch (NullPointerException expected) {}+ });+// ensure good docs are still okIndexReader ir = iw.getReader();assertEquals(3, ir.numDocs());+ir.close();iw.close();dir.close();@@ -2133,7 +2127,7 @@ public class TestIndexWriter extends LuceneTestCase {public void testIterableThrowsException2() throws IOException {Directory dir = newDirectory();IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())));- try {+ Exception expected = expectThrows(Exception.class, () -> {w.addDocuments(new Iterable<Document>() {@Overridepublic Iterator<Document> iterator() {@@ -2154,10 +2148,9 @@ public class TestIndexWriter extends LuceneTestCase {};}});- } catch (Exception e) {- assertNotNull(e.getMessage());- assertEquals("boom", e.getMessage());- }+ });+ assertEquals("boom", expected.getMessage());+w.close();IOUtils.close(dir);}@@ -2358,12 +2351,10 @@ public class TestIndexWriter extends LuceneTestCase {Document doc = new Document();doc.add(new SortedDocValuesField("dv", new BytesRef("foo!")));doc.add(new SortedDocValuesField("dv", new BytesRef("bar!")));- try {+ expectThrows(IllegalArgumentException.class, () -> {iwriter.addDocument(doc);- fail("didn't hit expected exception");- } catch (IllegalArgumentException expected) {- // expected- }+ });+iwriter.commit();assertFalse(iwriter.hasUncommittedChanges());iwriter.close();@@ -2733,19 +2724,15 @@ public class TestIndexWriter extends LuceneTestCase {assertTrue(dir.checkPendingDeletions());// make sure we get NFSF if we try to delete and already-pending-delete file:- try {+ expectThrows(NoSuchFileException.class, () -> {dir.deleteFile("segments_1");- fail("didn't hit exception");- } catch (NoSuchFileException nfse) {- // expected- }+ });++ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ new IndexWriter(dir, new IndexWriterConfig(new MockAnalyzer(random())));+ });+ assertTrue(expected.getMessage().contains("still has pending deleted files; cannot initialize IndexWriter"));- iwc = new IndexWriterConfig(new MockAnalyzer(random()));- try {- w = new IndexWriter(dir, iwc);- } catch (IllegalArgumentException iae) {- assertTrue(iae.getMessage().contains("still has pending deleted files; cannot initialize IndexWriter"));- }in.close();}}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterCommit.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterCommit.javaindex 5ae0e693ba0..ae076417c07 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterCommit.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterCommit.java@@ -486,12 +486,10 @@ public class TestIndexWriterCommit extends LuceneTestCase {// new index.Directory dir = newDirectory();IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())));- try {+ expectThrows(IndexNotFoundException.class, () -> {DirectoryReader.listCommits(dir);- fail("listCommits should have thrown an exception over empty index");- } catch (IndexNotFoundException e) {- // that's expected !- }+ });+// No changes still should generate a commit, because it's a new index.writer.close();assertEquals("expected 1 commits!", 1, DirectoryReader.listCommits(dir).size());@@ -673,15 +671,14 @@ public class TestIndexWriterCommit extends LuceneTestCase {Directory dir = newDirectory();IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random())));w.addDocument(new Document());+w.prepareCommit();- try {+ expectThrows(IllegalStateException.class, () -> {w.close();- fail("didn't hit exception");- } catch (IllegalStateException ise) {- // expected- }+ });w.commit();w.close();+DirectoryReader r = DirectoryReader.open(dir);assertEquals(1, r.maxDoc());r.close();diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterConfig.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterConfig.javaindex 3d85f0cf8fa..2ffdce71b5a 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterConfig.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterConfig.java@@ -142,12 +142,9 @@ public class TestIndexWriterConfig extends LuceneTestCase {new RandomIndexWriter(random(), dir, conf).close();// this should fail- try {+ expectThrows(IllegalStateException.class, () -> {assertNotNull(new RandomIndexWriter(random(), dir, conf));- fail("should have hit AlreadySetException");- } catch (IllegalStateException ise) {- // expected- }+ });dir.close();}@@ -213,96 +210,66 @@ public class TestIndexWriterConfig extends LuceneTestCase {assertEquals(KeepOnlyLastCommitDeletionPolicy.class, conf.getIndexDeletionPolicy().getClass());conf.setIndexDeletionPolicy(new SnapshotDeletionPolicy(null));assertEquals(SnapshotDeletionPolicy.class, conf.getIndexDeletionPolicy().getClass());- try {+ expectThrows(IllegalArgumentException.class, () -> {conf.setIndexDeletionPolicy(null);- fail();- } catch (IllegalArgumentException e) {- // ok- }+ });// Test MergeSchedulerassertEquals(ConcurrentMergeScheduler.class, conf.getMergeScheduler().getClass());conf.setMergeScheduler(new SerialMergeScheduler());assertEquals(SerialMergeScheduler.class, conf.getMergeScheduler().getClass());- try {+ expectThrows(IllegalArgumentException.class, () -> {conf.setMergeScheduler(null);- fail();- } catch (IllegalArgumentException e) {- // ok- }+ });// Test Similarity:// we shouldnt assert what the default is, just that it's not null.assertTrue(IndexSearcher.getDefaultSimilarity() == conf.getSimilarity());conf.setSimilarity(new MySimilarity());assertEquals(MySimilarity.class, conf.getSimilarity().getClass());- try {+ expectThrows(IllegalArgumentException.class, () -> {conf.setSimilarity(null);- fail();- } catch (IllegalArgumentException e) {- // ok- }+ });// Test IndexingChainassertTrue(DocumentsWriterPerThread.defaultIndexingChain == conf.getIndexingChain());- try {+ expectThrows(IllegalArgumentException.class, () -> {conf.setMaxBufferedDeleteTerms(0);- fail("should not have succeeded to set maxBufferedDeleteTerms to 0");- } catch (IllegalArgumentException e) {- // this is expected- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {conf.setMaxBufferedDocs(1);- fail("should not have succeeded to set maxBufferedDocs to 1");- } catch (IllegalArgumentException e) {- // this is expected- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {// Disable both MAX_BUF_DOCS and RAM_SIZE_MBconf.setMaxBufferedDocs(4);conf.setRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH);conf.setMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH);- fail("should not have succeeded to disable maxBufferedDocs when ramBufferSizeMB is disabled as well");- } catch (IllegalArgumentException e) {- // this is expected- }+ });conf.setRAMBufferSizeMB(IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB);conf.setMaxBufferedDocs(IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS);- try {+ expectThrows(IllegalArgumentException.class, () -> {conf.setRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH);- fail("should not have succeeded to disable ramBufferSizeMB when maxBufferedDocs is disabled as well");- } catch (IllegalArgumentException e) {- // this is expected- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {conf.setRAMPerThreadHardLimitMB(2048);- fail("should not have succeeded to set RAMPerThreadHardLimitMB to >= 2048");- } catch (IllegalArgumentException e) {- // this is expected- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {conf.setRAMPerThreadHardLimitMB(0);- fail("should not have succeeded to set RAMPerThreadHardLimitMB to 0");- } catch (IllegalArgumentException e) {- // this is expected- }+ });// Test MergePolicyassertEquals(TieredMergePolicy.class, conf.getMergePolicy().getClass());conf.setMergePolicy(new LogDocMergePolicy());assertEquals(LogDocMergePolicy.class, conf.getMergePolicy().getClass());- try {+ expectThrows(IllegalArgumentException.class, () -> {conf.setMergePolicy(null);- fail();- } catch (IllegalArgumentException e) {- // ok- }+ });}public void testLiveChangeToCFS() throws Exception {diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterDelete.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterDelete.javaindex 27295bfb67d..14dac59ed3f 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterDelete.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterDelete.java@@ -838,23 +838,18 @@ public class TestIndexWriterDelete extends LuceneTestCase {// case, creation of the cfs file happens next so we// need the doc (to test that it's okay that we don't// lose deletes if failing while creating the cfs file)- boolean failed = false;- try {- if (VERBOSE) {- System.out.println("TEST: now commit for failure");- }++ if (VERBOSE) {+ System.out.println("TEST: now commit for failure");+ }+ RuntimeException expected = expectThrows(RuntimeException.class, () -> {modifier.commit();- } catch (RuntimeException ioe) {- // expected- if (VERBOSE) {- System.out.println("TEST: hit exc:");- ioe.printStackTrace(System.out);- }- failed = true;+ });+ if (VERBOSE) {+ System.out.println("TEST: hit exc:");+ expected.printStackTrace(System.out);}- assertTrue(failed);-// The commit above failed, so we need to retry it (which will// succeed, because the failure is a one-shot)diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions.javaindex 07c78dc9500..49923389a45 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions.java@@ -377,13 +377,12 @@ public class TestIndexWriterExceptions extends LuceneTestCase {Document doc = new Document();doc.add(newTextField("field", "a field", Field.Store.YES));w.addDocument(doc);+testPoint.doFail = true;- try {+ expectThrows(RuntimeException.class, () -> {w.addDocument(doc);- fail("did not hit exception");- } catch (RuntimeException re) {- // expected- }+ });+w.close();dir.close();}@@ -418,12 +417,10 @@ public class TestIndexWriterExceptions extends LuceneTestCase {Document crashDoc = new Document();crashDoc.add(newTextField("crash", "do it on token 4", Field.Store.YES));doCrash.set(true);- try {+ expectThrows(IOException.class, () -> {w.addDocument(crashDoc);- fail("did not hit expected exception");- } catch (IOException ioe) {- // expected- }+ });+w.addDocument(doc);w.close();dir.close();@@ -508,17 +505,15 @@ public class TestIndexWriterExceptions extends LuceneTestCase {IndexWriter writer = new IndexWriter(dir, conf);- Document doc = new Document();+ Document brokenDoc = new Document();String contents = "aa bb cc dd ee ff gg hh ii jj kk";- doc.add(newTextField("content", contents, Field.Store.NO));- try {- writer.addDocument(doc);- fail("did not hit expected exception");- } catch (Exception e) {- }+ brokenDoc.add(newTextField("content", contents, Field.Store.NO));+ expectThrows(Exception.class, () -> {+ writer.addDocument(brokenDoc);+ });// Make sure we can add another normal document- doc = new Document();+ Document doc = new Document();doc.add(newTextField("content", "aa bb cc dd", Field.Store.NO));writer.addDocument(doc);@@ -604,17 +599,18 @@ public class TestIndexWriterExceptions extends LuceneTestCase {doc.add(newTextField("content", contents, Field.Store.NO));boolean hitError = false;writer.addDocument(doc);- try {++ expectThrows(IOException.class, () -> {writer.addDocument(doc);- fail("did not hit exception");- } catch (IOException ioe) {- // only one flush should fail:- assertFalse(hitError);- hitError = true;- assertTrue(writer.deleter.isClosed());- assertTrue(writer.isClosed());- }+ });++ // only one flush should fail:+ assertFalse(hitError);+ hitError = true;+ assertTrue(writer.deleter.isClosed());+ assertTrue(writer.isClosed());assertFalse(DirectoryReader.indexExists(dir));+dir.close();}@@ -750,17 +746,15 @@ public class TestIndexWriterExceptions extends LuceneTestCase {writer.addDocument(doc);doc.add(newField("crash", "this should crash after 4 terms", DocCopyIterator.custom5));doc.add(newField("other", "this will not get indexed", DocCopyIterator.custom5));- try {+ expectThrows(IOException.class, () -> {writer.addDocument(doc);- fail("did not hit expected exception");- } catch (IOException ioe) {- }+ });if (0 == finalI) {- doc = new Document();- doc.add(newField("contents", "here are some contents", DocCopyIterator.custom5));- writer.addDocument(doc);- writer.addDocument(doc);+ Document extraDoc = new Document();+ extraDoc.add(newField("contents", "here are some contents", DocCopyIterator.custom5));+ writer.addDocument(extraDoc);+ writer.addDocument(extraDoc);}}} catch (Throwable t) {@@ -956,14 +950,10 @@ public class TestIndexWriterExceptions extends LuceneTestCase {doc.add(newTextField("field", "a field", Field.Store.YES));w.addDocument(doc);dir.failOn(failure);- try {+ expectThrows(RuntimeException.class, () -> {w.close();- fail();- } catch (IOException ioe) {- fail("expected only RuntimeException");- } catch (RuntimeException re) {- // Expected- }+ });+assertTrue("failOnCommit=" + failure.failOnCommit + " failOnDeleteFile=" + failure.failOnDeleteFile, failure.failOnCommit && failure.failOnDeleteFile);w.rollback();String files[] = dir.listAll();@@ -1040,11 +1030,9 @@ public class TestIndexWriterExceptions extends LuceneTestCase {public void close() {}}));- try {+ expectThrows(OutOfMemoryError.class, () -> {writer.close();- fail("OutOfMemoryError expected");- }- catch (final OutOfMemoryError expected) {}+ });// throws IllegalStateEx w/o bug fixwriter.close();@@ -1076,23 +1064,19 @@ public class TestIndexWriterExceptions extends LuceneTestCase {}));writer.addDocument(new Document());- try {+ expectThrows(OutOfMemoryError.class, () -> {writer.commit();- fail("OutOfMemoryError expected");- }- catch (final OutOfMemoryError expected) {}+ });try {writer.close();- } catch (IllegalStateException ise) {- // expected+ } catch (IllegalArgumentException ok) {+ // ok}- try {+ expectThrows(AlreadyClosedException.class, () -> {writer.addDocument(new Document());- } catch (AlreadyClosedException ace) {- // expected- }+ });// IW should have done rollback() during close, since it hit OOME, and so no index should exist:assertFalse(DirectoryReader.indexExists(dir));@@ -1121,12 +1105,9 @@ public class TestIndexWriterExceptions extends LuceneTestCase {addDoc(w);testPoint.doFail = true;- try {+ expectThrows(RuntimeException.class, () -> {w.rollback();- fail("did not hit intentional RuntimeException");- } catch (RuntimeException re) {- // expected- }+ });testPoint.doFail = false;w.rollback();@@ -1162,11 +1143,9 @@ public class TestIndexWriterExceptions extends LuceneTestCase {out.close();in.close();- try {+ expectThrows(CorruptIndexException.class, () -> {DirectoryReader.open(dir);- fail("didn't get expected checksum error");- } catch (CorruptIndexException expected) {- }+ });dir.close();}@@ -1207,15 +1186,10 @@ public class TestIndexWriterExceptions extends LuceneTestCase {out.close();dir.deleteFile(fileNameIn);- IndexReader reader = null;- try {- reader = DirectoryReader.open(dir);- fail("reader did not hit IOException on opening a corrupt index");- } catch (Exception e) {- }- if (reader != null) {- reader.close();- }+ expectThrows(Exception.class, () -> {+ DirectoryReader.open(dir);+ });+dir.close();}@@ -1262,15 +1236,10 @@ public class TestIndexWriterExceptions extends LuceneTestCase {assertTrue("failed to find cfs file to remove: ", corrupted);- IndexReader reader = null;- try {- reader = DirectoryReader.open(dir);- fail("reader did not hit IOException on opening a corrupt index");- } catch (Exception e) {- }- if (reader != null) {- reader.close();- }+ expectThrows(Exception.class, () -> {+ DirectoryReader.open(dir);+ });+dir.close();}@@ -1398,14 +1367,11 @@ public class TestIndexWriterExceptions extends LuceneTestCase {f.setTokenStream(new CrashingFilter("crash", tokenizer));}}- try {++ IOException expected = expectThrows(IOException.class, () -> {w.addDocuments(docs);- // BUG: CrashingFilter didn't- fail("did not hit expected exception");- } catch (IOException ioe) {- // expected- assertEquals(CRASH_FAIL_MESSAGE, ioe.getMessage());- }+ });+ assertEquals(CRASH_FAIL_MESSAGE, expected.getMessage());final int numDocs2 = random().nextInt(25);for(int docCount=0;docCount<numDocs2;docCount++) {@@ -1475,14 +1441,10 @@ public class TestIndexWriterExceptions extends LuceneTestCase {}}- try {+ IOException expected = expectThrows(IOException.class, () -> {w.updateDocuments(new Term("subid", "subs"), docs);- // BUG: CrashingFilter didn't- fail("did not hit expected exception");- } catch (IOException ioe) {- // expected- assertEquals(CRASH_FAIL_MESSAGE, ioe.getMessage());- }+ });+ assertEquals(CRASH_FAIL_MESSAGE, expected.getMessage());final int numDocs4 = random().nextInt(25);for(int docCount=0;docCount<numDocs4;docCount++) {@@ -1512,13 +1474,13 @@ public class TestIndexWriterExceptions extends LuceneTestCase {// add good documentDocument doc = new Document();iw.addDocument(doc);- try {+ expectThrows(IllegalArgumentException.class, () -> {// set to null valueString value = null;doc.add(new StoredField("foo", value));iw.addDocument(doc);- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {}+ });+assertNull(iw.getTragicException());iw.close();// make sure we see our good doc@@ -1538,12 +1500,12 @@ public class TestIndexWriterExceptions extends LuceneTestCase {Field theField = new StoredField("foo", "hello", StoredField.TYPE);doc.add(theField);iw.addDocument(doc);- try {+ expectThrows(IllegalArgumentException.class, () -> {// set to null valuetheField.setStringValue(null);iw.addDocument(doc);- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {}+ });+assertNull(iw.getTragicException());iw.close();// make sure we see our good doc@@ -1562,14 +1524,14 @@ public class TestIndexWriterExceptions extends LuceneTestCase {Document doc = new Document();iw.addDocument(doc);- try {+ expectThrows(NullPointerException.class, () -> {// set to null valuebyte v[] = null;Field theField = new StoredField("foo", v);doc.add(theField);iw.addDocument(doc);- fail("didn't get expected exception");- } catch (NullPointerException expected) {}+ });+assertNull(iw.getTragicException());iw.close();// make sure we see our good doc@@ -1589,13 +1551,13 @@ public class TestIndexWriterExceptions extends LuceneTestCase {Field theField = new StoredField("foo", new BytesRef("hello").bytes);doc.add(theField);iw.addDocument(doc);- try {+ expectThrows(NullPointerException.class, () -> {// set to null valuebyte v[] = null;theField.setBytesValue(v);iw.addDocument(doc);- fail("didn't get expected exception");- } catch (NullPointerException expected) {}+ });+assertNull(iw.getTragicException());iw.close();// make sure we see our good doc@@ -1614,14 +1576,15 @@ public class TestIndexWriterExceptions extends LuceneTestCase {Document doc = new Document();iw.addDocument(doc);- try {+ expectThrows(IllegalArgumentException.class, () -> {// set to null valueBytesRef v = null;Field theField = new StoredField("foo", v);doc.add(theField);iw.addDocument(doc);fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {}+ });+assertNull(iw.getTragicException());iw.close();// make sure we see our good doc@@ -1641,13 +1604,14 @@ public class TestIndexWriterExceptions extends LuceneTestCase {Field theField = new StoredField("foo", new BytesRef("hello"));doc.add(theField);iw.addDocument(doc);- try {+ expectThrows(IllegalArgumentException.class, () -> {// set to null valueBytesRef v = null;theField.setBytesValue(v);iw.addDocument(doc);fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {}+ });+assertNull(iw.getTragicException());iw.close();// make sure we see our good doc@@ -1674,12 +1638,12 @@ public class TestIndexWriterExceptions extends LuceneTestCase {// add good documentDocument doc = new Document();iw.addDocument(doc);- try {+ expectThrows(IllegalArgumentException.class, () -> {doc.add(newTextField("foo", "bar", Field.Store.NO));doc.add(newTextField("foo", "bar", Field.Store.NO));iw.addDocument(doc);- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {}+ });+assertNull(iw.getTragicException());iw.close();@@ -1716,11 +1680,9 @@ public class TestIndexWriterExceptions extends LuceneTestCase {iw.addDocument(new Document());iw.close();uoe.doFail = true;- try {+ expectThrows(UnsupportedOperationException.class, () -> {new IndexWriter(d, newIndexWriterConfig(null));- fail("should have gotten a UOE");- } catch (UnsupportedOperationException expected) {- }+ });uoe.doFail = false;d.close();@@ -1736,8 +1698,7 @@ public class TestIndexWriterExceptions extends LuceneTestCase {doc.add(new TextField("field2", "sometext", Field.Store.NO));doc.add(new StringField("foo", "bar", Field.Store.NO));iw.addDocument(doc); // add an 'ok' document- try {- doc = new Document();+ expectThrows(UnsupportedOperationException.class, () -> {// try to boost with norms omittedList<IndexableField> list = new ArrayList<>();list.add(new IndexableField() {@@ -1782,10 +1743,8 @@ public class TestIndexWriterExceptions extends LuceneTestCase {}});iw.addDocument(list);- fail("didn't get any exception, boost silently discarded");- } catch (UnsupportedOperationException expected) {- // expected- }+ });+DirectoryReader ir = DirectoryReader.open(iw);assertEquals(1, ir.numDocs());assertEquals("sometext", ir.document(0).get("field1"));@@ -2146,12 +2105,12 @@ public class TestIndexWriterExceptions extends LuceneTestCase {return true;}}, ft));- try {++ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {iw.addDocument(doc);- fail("didn't hit exception");- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("too many tokens"));- }+ });+ assertTrue(expected.getMessage().contains("too many tokens"));+iw.close();dir.close();}@@ -2201,12 +2160,10 @@ public class TestIndexWriterExceptions extends LuceneTestCase {iw.prepareCommit();}- try {+ RuntimeException expected = expectThrows(RuntimeException.class, () -> {iw.rollback();- fail();- } catch (RuntimeException expected) {- assertEquals("BOOM!", expected.getMessage());- }+ });+ assertEquals("BOOM!", expected.getMessage());r.close();@@ -2275,6 +2232,7 @@ public class TestIndexWriterExceptions extends LuceneTestCase {try {iw.rollback();} catch (FakeIOException expected) {+ // ok, we randomly hit exc here}r.close();diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterFromReader.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterFromReader.javaindex e63894f1089..5ee95203ddc 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterFromReader.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterFromReader.java@@ -97,13 +97,11 @@ public class TestIndexWriterFromReader extends LuceneTestCase {IndexWriterConfig iwc = newIndexWriterConfig();iwc.setIndexCommit(r.getIndexCommit());- try {++ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new IndexWriter(dir, iwc);- fail("did not hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- assertEquals("cannot use IndexWriterConfig.setIndexCommit() when index has no commit", iae.getMessage());- }+ });+ assertEquals("cannot use IndexWriterConfig.setIndexCommit() when index has no commit", expected.getMessage());r.close();dir.close();@@ -123,13 +121,12 @@ public class TestIndexWriterFromReader extends LuceneTestCase {IndexWriterConfig iwc = newIndexWriterConfig();iwc.setIndexCommit(r.getIndexCommit());- try {++ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new IndexWriter(dir, iwc);- fail("did not hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- assertTrue(iae.getMessage().contains("the provided reader is stale: its prior commit file"));- }+ });+ assertTrue(expected.getMessage().contains("the provided reader is stale: its prior commit file"));+r.close();dir.close();}@@ -151,13 +148,11 @@ public class TestIndexWriterFromReader extends LuceneTestCase {IndexWriterConfig iwc = newIndexWriterConfig();iwc.setIndexCommit(r.getIndexCommit());- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new IndexWriter(dir, iwc);- fail("did not hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- assertTrue(iae.getMessage().contains("the provided reader is stale: its prior commit file"));- }+ });+ assertTrue(expected.getMessage().contains("the provided reader is stale: its prior commit file"));+r.close();dir.close();}@@ -351,13 +346,11 @@ public class TestIndexWriterFromReader extends LuceneTestCase {IndexWriterConfig iwc = newIndexWriterConfig();iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);iwc.setIndexCommit(r.getIndexCommit());- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new IndexWriter(dir, iwc);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- assertEquals("cannot use IndexWriterConfig.setIndexCommit() with OpenMode.CREATE", iae.getMessage());- }+ });+ assertEquals("cannot use IndexWriterConfig.setIndexCommit() with OpenMode.CREATE", expected.getMessage());+IOUtils.close(r, dir);}@@ -375,12 +368,10 @@ public class TestIndexWriterFromReader extends LuceneTestCase {IndexWriterConfig iwc = newIndexWriterConfig();iwc.setIndexCommit(commit);- try {+ expectThrows(AlreadyClosedException.class, () -> {new IndexWriter(dir, iwc);- fail("did not hit exception");- } catch (AlreadyClosedException ace) {- // expected- }+ });+IOUtils.close(r, dir);}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterMaxDocs.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterMaxDocs.javaindex 665faaeed31..4fd7550d5b0 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterMaxDocs.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterMaxDocs.java@@ -94,12 +94,10 @@ public class TestIndexWriterMaxDocs extends LuceneTestCase {}// 11th document should fail:- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(new Document());- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w.close();dir.close();} finally {@@ -117,12 +115,10 @@ public class TestIndexWriterMaxDocs extends LuceneTestCase {}// 11th document should fail:- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocuments(Collections.singletonList(new Document()));- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w.close();dir.close();} finally {@@ -140,12 +136,10 @@ public class TestIndexWriterMaxDocs extends LuceneTestCase {}// 11th document should fail:- try {+ expectThrows(IllegalArgumentException.class, () -> {w.updateDocument(new Term("field", "foo"), new Document());- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w.close();dir.close();} finally {@@ -163,12 +157,10 @@ public class TestIndexWriterMaxDocs extends LuceneTestCase {}// 11th document should fail:- try {+ expectThrows(IllegalArgumentException.class, () -> {w.updateDocuments(new Term("field", "foo"), Collections.singletonList(new Document()));- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w.close();dir.close();} finally {@@ -202,12 +194,10 @@ public class TestIndexWriterMaxDocs extends LuceneTestCase {}// 11th document should fail:- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(new Document());- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w.close();dir.close();} finally {@@ -248,12 +238,10 @@ public class TestIndexWriterMaxDocs extends LuceneTestCase {}// 11th document should fail:- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(new Document());- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w.close();dir.close();} finally {@@ -274,20 +262,16 @@ public class TestIndexWriterMaxDocs extends LuceneTestCase {Directory dir2 = newDirectory();IndexWriter w2 = new IndexWriter(dir2, new IndexWriterConfig(null));w2.addDocument(new Document());- try {+ expectThrows(IllegalArgumentException.class, () -> {w2.addIndexes(new Directory[] {dir});- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+assertEquals(1, w2.maxDoc());DirectoryReader ir = DirectoryReader.open(dir);- try {+ expectThrows(IllegalArgumentException.class, () -> {TestUtil.addIndexesSlowly(w2, ir);- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w2.close();ir.close();dir.close();@@ -362,12 +346,10 @@ public class TestIndexWriterMaxDocs extends LuceneTestCase {Arrays.fill(subReaders, ir);subReaders[subReaders.length-1] = ir2;- try {+ expectThrows(IllegalArgumentException.class, () -> {new MultiReader(subReaders);- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+ir.close();ir2.close();dir.close();@@ -472,12 +454,9 @@ public class TestIndexWriterMaxDocs extends LuceneTestCase {}public void testTooLargeMaxDocs() throws Exception {- try {+ expectThrows(IllegalArgumentException.class, () -> {IndexWriter.setMaxDocs(Integer.MAX_VALUE);- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });}// LUCENE-6299@@ -487,20 +466,16 @@ public class TestIndexWriterMaxDocs extends LuceneTestCase {Directory dir = newDirectory();IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(null));w.addDocument(new Document());- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(new Document());- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w.deleteAll();w.addDocument(new Document());- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(new Document());- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w.close();dir.close();} finally {@@ -517,21 +492,17 @@ public class TestIndexWriterMaxDocs extends LuceneTestCase {w.addDocument(new Document());w.getReader().close();w.addDocument(new Document());- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(new Document());- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w.deleteAll();w.addDocument(new Document());w.addDocument(new Document());- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(new Document());- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w.close();dir.close();} finally {@@ -548,21 +519,17 @@ public class TestIndexWriterMaxDocs extends LuceneTestCase {w.addDocument(new Document());w.commit();w.addDocument(new Document());- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(new Document());- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w.deleteAll();w.addDocument(new Document());w.addDocument(new Document());- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(new Document());- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w.close();dir.close();} finally {@@ -601,22 +568,18 @@ public class TestIndexWriterMaxDocs extends LuceneTestCase {thread.join();}- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(new Document());- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w.deleteAll();for(int i=0;i<limit;i++) {w.addDocument(new Document());}- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(new Document());- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w.close();dir.close();} finally {@@ -632,24 +595,21 @@ public class TestIndexWriterMaxDocs extends LuceneTestCase {IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(null));w.addDocument(new Document());w.close();- w = new IndexWriter(dir, new IndexWriterConfig(null));- w.addDocument(new Document());- try {- w.addDocument(new Document());- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }- w.deleteAll();- w.addDocument(new Document());- w.addDocument(new Document());- try {- w.addDocument(new Document());- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }- w.close();++ IndexWriter w2 = new IndexWriter(dir, new IndexWriterConfig(null));+ w2.addDocument(new Document());+ expectThrows(IllegalArgumentException.class, () -> {+ w2.addDocument(new Document());+ });++ w2.deleteAll();+ w2.addDocument(new Document());+ w2.addDocument(new Document());+ expectThrows(IllegalArgumentException.class, () -> {+ w2.addDocument(new Document());+ });++ w2.close();dir.close();} finally {restoreIndexWriterMaxDocs();@@ -664,14 +624,12 @@ public class TestIndexWriterMaxDocs extends LuceneTestCase {IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(null));w.addDocument(new Document());w.close();- w = new IndexWriter(dir, new IndexWriterConfig(null));- try {- w.addDocument(new Document());- fail("didn't hit exception");- } catch (IllegalArgumentException iae) {- // expected- }- w.close();+ IndexWriter w2 = new IndexWriter(dir, new IndexWriterConfig(null));+ expectThrows(IllegalArgumentException.class, () -> {+ w2.addDocument(new Document());+ });++ w2.close();dir.close();} finally {restoreIndexWriterMaxDocs();@@ -687,11 +645,10 @@ public class TestIndexWriterMaxDocs extends LuceneTestCase {w.close();setIndexWriterMaxDocs(1);- try {- DirectoryReader.open(dir);- fail("didn't hit exception");- } catch (CorruptIndexException cie) {- // expected+ try {+ expectThrows(CorruptIndexException.class, () -> {+ DirectoryReader.open(dir);+ });} finally {restoreIndexWriterMaxDocs();}@@ -708,11 +665,10 @@ public class TestIndexWriterMaxDocs extends LuceneTestCase {w.close();setIndexWriterMaxDocs(1);- try {- new IndexWriter(dir, new IndexWriterConfig(null));- fail("didn't hit exception");- } catch (CorruptIndexException cie) {- // expected+ try {+ expectThrows(CorruptIndexException.class, () -> {+ new IndexWriter(dir, new IndexWriterConfig(null));+ });} finally {restoreIndexWriterMaxDocs();}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterMergePolicy.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterMergePolicy.javaindex d03de7e6994..2d5680c15da 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterMergePolicy.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterMergePolicy.java@@ -287,12 +287,9 @@ public class TestIndexWriterMergePolicy extends LuceneTestCase {lmp.setMaxCFSSegmentSizeMB(Long.MAX_VALUE/1024/1024.);assertEquals(Long.MAX_VALUE/1024/1024., lmp.getMaxCFSSegmentSizeMB(), EPSILON*Long.MAX_VALUE);- try {+ expectThrows(IllegalArgumentException.class, () -> {lmp.setMaxCFSSegmentSizeMB(-2.0);- fail("Didn't throw IllegalArgumentException");- } catch (IllegalArgumentException iae) {- // pass- }+ });// TODO: Add more checks for other non-double setters!}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOnDiskFull.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOnDiskFull.javaindex eecb3bd898c..b7d0b29ca64 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOnDiskFull.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOnDiskFull.java@@ -523,21 +523,16 @@ public class TestIndexWriterOnDiskFull extends LuceneTestCase {ftdm.setDoFail();dir.failOn(ftdm);- try {+ expectThrows(IOException.class, () -> {w.commit();- fail("fake disk full IOExceptions not hit");- } catch (IOException ioe) {- // expected- assertTrue(ftdm.didFail1 || ftdm.didFail2);- }+ });+ assertTrue(ftdm.didFail1 || ftdm.didFail2);+TestUtil.checkIndex(dir);ftdm.clearDoFail();- try {+ expectThrows(AlreadyClosedException.class, () -> {w.addDocument(doc);- fail("writer was not closed by merge exception");- } catch (AlreadyClosedException ace) {- // expected- }+ });dir.close();}@@ -556,13 +551,12 @@ public class TestIndexWriterOnDiskFull extends LuceneTestCase {final Document doc = new Document();FieldType customType = new FieldType(TextField.TYPE_STORED);doc.add(newField("field", "aaa bbb ccc ddd eee fff ggg hhh iii jjj", customType));- try {+ expectThrows(IOException.class, () -> {writer.addDocument(doc);- fail("did not hit disk full");- } catch (IOException ioe) {- assertTrue(writer.deleter.isClosed());- assertTrue(writer.isClosed());- }+ });+ assertTrue(writer.deleter.isClosed());+ assertTrue(writer.isClosed());+dir.close();}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterReader.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterReader.javaindex 173128eae6f..584e03cd71a 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterReader.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterReader.java@@ -709,12 +709,11 @@ public class TestIndexWriterReader extends LuceneTestCase {Query q = new TermQuery(new Term("indexname", "test"));IndexSearcher searcher = newSearcher(r);assertEquals(100, searcher.search(q, 10).totalHits);- try {++ expectThrows(AlreadyClosedException.class, () -> {DirectoryReader.openIfChanged(r);- fail("failed to hit AlreadyClosedException");- } catch (AlreadyClosedException ace) {- // expected- }+ });+r.close();dir1.close();}@@ -1112,14 +1111,9 @@ public class TestIndexWriterReader extends LuceneTestCase {// other NRT reader, since it is already marked closed!for (int i = 0; i < 2; i++) {shouldFail.set(true);- try {+ expectThrows(FakeIOException.class, () -> {writer.getReader().close();- } catch (FakeIOException e) {- // expected- if (VERBOSE) {- System.out.println("hit expected fake IOE");- }- }+ });}writer.close();diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterWithThreads.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterWithThreads.javaindex 72029cb5efa..34c5a52661c 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterWithThreads.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterWithThreads.java@@ -365,22 +365,20 @@ public class TestIndexWriterWithThreads extends LuceneTestCase {dir.failOn(failure);failure.setDoFail();- try {+ expectThrows(IOException.class, () -> {writer.addDocument(doc);writer.addDocument(doc);writer.commit();- fail("did not hit exception");- } catch (IOException ioe) {- }+ });+failure.clearDoFail();- try {+ expectThrows(AlreadyClosedException.class, () -> {writer.addDocument(doc);writer.commit();writer.close();- } catch (AlreadyClosedException ace) {- // OK: abort closes the writer- assertTrue(writer.deleter.isClosed());- }+ });++ assertTrue(writer.deleter.isClosed());dir.close();}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestMaxPosition.java b/lucene/core/src/test/org/apache/lucene/index/TestMaxPosition.javaindex f8c7ceb759c..c65082cadb0 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestMaxPosition.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestMaxPosition.java@@ -45,12 +45,9 @@ public class TestMaxPosition extends LuceneTestCase {t2.setPayload(new BytesRef(new byte[] { 0x1 } ));}doc.add(new TextField("foo", new CannedTokenStream(new Token[] {t1, t2})));- try {+ expectThrows(IllegalArgumentException.class, () -> {iw.addDocument(doc);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });// Document should not be visible:IndexReader r = DirectoryReader.open(iw);diff --git a/lucene/core/src/test/org/apache/lucene/index/TestNumericDocValuesUpdates.java b/lucene/core/src/test/org/apache/lucene/index/TestNumericDocValuesUpdates.javaindex 33666463da1..727f6ff7fcb 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestNumericDocValuesUpdates.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestNumericDocValuesUpdates.java@@ -421,19 +421,13 @@ public class TestNumericDocValuesUpdates extends LuceneTestCase {writer.commit();writer.addDocument(doc); // in-memory document- try {+ expectThrows(IllegalArgumentException.class, () -> {writer.updateNumericDocValue(new Term("key", "doc"), "ndv", 17L);- fail("should not have allowed creating new fields through update");- } catch (IllegalArgumentException e) {- // ok- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {writer.updateNumericDocValue(new Term("key", "doc"), "foo", 17L);- fail("should not have allowed updating an existing field to numeric-dv");- } catch (IllegalArgumentException e) {- // ok- }+ });writer.close();dir.close();diff --git a/lucene/core/src/test/org/apache/lucene/index/TestOmitTf.java b/lucene/core/src/test/org/apache/lucene/index/TestOmitTf.javaindex 741c1438443..807c704ca0f 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestOmitTf.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestOmitTf.java@@ -306,17 +306,15 @@ public class TestOmitTf extends LuceneTestCase {TermQuery q4 = new TermQuery(d);PhraseQuery pq = new PhraseQuery(a.field(), a.bytes(), c.bytes());- try {+ Exception expected = expectThrows(Exception.class, () -> {searcher.search(pq, 10);- fail("did not hit expected exception");- } catch (Exception e) {- Throwable cause = e;- // If the searcher uses an executor service, the IAE is wrapped into other exceptions- while (cause.getCause() != null) {- cause = cause.getCause();- }- assertTrue("Expected an IAE, got " + cause, cause instanceof IllegalStateException);+ });+ Throwable cause = expected;+ // If the searcher uses an executor service, the IAE is wrapped into other exceptions+ while (cause.getCause() != null) {+ cause = cause.getCause();}+ assertTrue("Expected an IAE, got " + cause, cause instanceof IllegalStateException);searcher.search(q1,new CountingHitCollector() {diff --git a/lucene/core/src/test/org/apache/lucene/index/TestParallelCompositeReader.java b/lucene/core/src/test/org/apache/lucene/index/TestParallelCompositeReader.javaindex e7d735c25d6..7078380c938 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestParallelCompositeReader.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestParallelCompositeReader.java@@ -203,19 +203,13 @@ public class TestParallelCompositeReader extends LuceneTestCase {ir1.close();assertEquals("refCount of synthetic subreader should be unchanged", 1, psub.getRefCount());- try {+ expectThrows(AlreadyClosedException.class, () -> {psub.document(0);- fail("Subreader should be already closed because inner reader was closed!");- } catch (AlreadyClosedException e) {- // pass- }+ });- try {+ expectThrows(AlreadyClosedException.class, () -> {pr.document(0);- fail("ParallelCompositeReader should be already closed because inner reader was closed!");- } catch (AlreadyClosedException e) {- // pass- }+ });// noop:pr.close();@@ -238,18 +232,15 @@ public class TestParallelCompositeReader extends LuceneTestCase {DirectoryReader ir1 = DirectoryReader.open(dir1),ir2 = DirectoryReader.open(dir2);- try {++ expectThrows(IllegalArgumentException.class, () -> {new ParallelCompositeReader(ir1, ir2);- fail("didn't get expected exception: indexes don't have same number of documents");- } catch (IllegalArgumentException e) {- // expected exception- }- try {+ });++ expectThrows(IllegalArgumentException.class, () -> {new ParallelCompositeReader(random().nextBoolean(), ir1, ir2);- fail("didn't get expected exception: indexes don't have same number of documents");- } catch (IllegalArgumentException e) {- // expected exception- }+ });+assertEquals(1, ir1.getRefCount());assertEquals(1, ir2.getRefCount());ir1.close();@@ -267,18 +258,14 @@ public class TestParallelCompositeReader extends LuceneTestCase {DirectoryReader ir1 = DirectoryReader.open(dir1),ir2 = DirectoryReader.open(dir2);CompositeReader[] readers = new CompositeReader[] {ir1, ir2};- try {+ expectThrows(IllegalArgumentException.class, () -> {new ParallelCompositeReader(readers);- fail("didn't get expected exception: indexes don't have same subreader structure");- } catch (IllegalArgumentException e) {- // expected exception- }- try {+ });++ expectThrows(IllegalArgumentException.class, () -> {new ParallelCompositeReader(random().nextBoolean(), readers, readers);- fail("didn't get expected exception: indexes don't have same subreader structure");- } catch (IllegalArgumentException e) {- // expected exception- }+ });+assertEquals(1, ir1.getRefCount());assertEquals(1, ir2.getRefCount());ir1.close();@@ -296,18 +283,15 @@ public class TestParallelCompositeReader extends LuceneTestCase {CompositeReader ir1 = new MultiReader(DirectoryReader.open(dir1), SlowCompositeReaderWrapper.wrap(DirectoryReader.open(dir1))),ir2 = new MultiReader(DirectoryReader.open(dir2), DirectoryReader.open(dir2));CompositeReader[] readers = new CompositeReader[] {ir1, ir2};- try {++ expectThrows(IllegalArgumentException.class, () -> {new ParallelCompositeReader(readers);- fail("didn't get expected exception: indexes don't have same subreader structure");- } catch (IllegalArgumentException e) {- // expected exception- }- try {+ });++ expectThrows(IllegalArgumentException.class, () -> {new ParallelCompositeReader(random().nextBoolean(), readers, readers);- fail("didn't get expected exception: indexes don't have same subreader structure");- } catch (IllegalArgumentException e) {- // expected exception- }+ });+assertEquals(1, ir1.getRefCount());assertEquals(1, ir2.getRefCount());ir1.close();@@ -373,14 +357,11 @@ public class TestParallelCompositeReader extends LuceneTestCase {pr.close();// no main readers- try {+ expectThrows(IllegalArgumentException.class, () -> {new ParallelCompositeReader(true,new CompositeReader[0],new CompositeReader[] {ir1});- fail("didn't get expected exception: need a non-empty main-reader array");- } catch (IllegalArgumentException iae) {- // pass- }+ });dir1.close();dir2.close();diff --git a/lucene/core/src/test/org/apache/lucene/index/TestParallelLeafReader.java b/lucene/core/src/test/org/apache/lucene/index/TestParallelLeafReader.javaindex ff6fab6d1ac..31aa603b474 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestParallelLeafReader.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestParallelLeafReader.java@@ -126,12 +126,10 @@ public class TestParallelLeafReader extends LuceneTestCase {ir1.close();- try {+ // should already be closed because inner reader is closed!+ expectThrows(AlreadyClosedException.class, () -> {pr.document(0);- fail("ParallelLeafReader should be already closed because inner reader was closed!");- } catch (AlreadyClosedException e) {- // pass- }+ });// noop:pr.close();@@ -154,21 +152,17 @@ public class TestParallelLeafReader extends LuceneTestCase {LeafReader ir1 = SlowCompositeReaderWrapper.wrap(DirectoryReader.open(dir1));LeafReader ir2 = SlowCompositeReaderWrapper.wrap(DirectoryReader.open(dir2));- try {+ // indexes don't have the same number of documents+ expectThrows(IllegalArgumentException.class, () -> {new ParallelLeafReader(ir1, ir2);- fail("didn't get exptected exception: indexes don't have same number of documents");- } catch (IllegalArgumentException e) {- // expected exception- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {new ParallelLeafReader(random().nextBoolean(),new LeafReader[] {ir1, ir2},new LeafReader[] {ir1, ir2});- fail("didn't get expected exception: indexes don't have same number of documents");- } catch (IllegalArgumentException e) {- // expected exception- }+ });+// check RefCountsassertEquals(1, ir1.getRefCount());assertEquals(1, ir2.getRefCount());@@ -230,14 +224,11 @@ public class TestParallelLeafReader extends LuceneTestCase {pr.close();// no main readers- try {+ expectThrows(IllegalArgumentException.class, () -> {new ParallelLeafReader(true,new LeafReader[0],new LeafReader[] {ir1});- fail("didn't get expected exception: need a non-empty main-reader array");- } catch (IllegalArgumentException iae) {- // pass- }+ });dir1.close();dir2.close();diff --git a/lucene/core/src/test/org/apache/lucene/index/TestPayloadsOnVectors.java b/lucene/core/src/test/org/apache/lucene/index/TestPayloadsOnVectors.javaindex 3b0117d1337..a90a5d25bbc 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestPayloadsOnVectors.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestPayloadsOnVectors.java@@ -133,12 +133,11 @@ public class TestPayloadsOnVectors extends LuceneTestCase {customType.setStoreTermVectorPayloads(true);customType.setStoreTermVectorOffsets(random().nextBoolean());doc.add(new Field("field", "foo", customType));- try {++ expectThrows(IllegalArgumentException.class, () -> {writer.addDocument(doc);- fail();- } catch (IllegalArgumentException expected) {- // expected- }+ });+writer.close();dir.close();}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestPersistentSnapshotDeletionPolicy.java b/lucene/core/src/test/org/apache/lucene/index/TestPersistentSnapshotDeletionPolicy.javaindex 0ace80469f1..f4a6024b676 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestPersistentSnapshotDeletionPolicy.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestPersistentSnapshotDeletionPolicy.java@@ -103,13 +103,12 @@ public class TestPersistentSnapshotDeletionPolicy extends TestSnapshotDeletionPo@Testpublic void testMissingSnapshots() throws Exception {Directory dir = newDirectory();- try {++ expectThrows(IllegalStateException.class, () -> {new PersistentSnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy(), dir, OpenMode.APPEND);- fail("did not hit expected exception");- } catch (IllegalStateException ise) {- // expected- }+ });+dir.close();}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestPointValues.java b/lucene/core/src/test/org/apache/lucene/index/TestPointValues.javaindex 0eb5e8feb94..3e1fe2d1ac8 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestPointValues.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestPointValues.java@@ -60,12 +60,10 @@ public class TestPointValues extends LuceneTestCase {Document doc = new Document();doc.add(new BinaryPoint("dim", new byte[4]));doc.add(new BinaryPoint("dim", new byte[4], new byte[4]));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);- } catch (IllegalArgumentException iae) {- // expected- assertEquals("cannot change point dimension count from 1 to 2 for field=\"dim\"", iae.getMessage());- }+ });+ assertEquals("cannot change point dimension count from 1 to 2 for field=\"dim\"", expected.getMessage());w.close();dir.close();}@@ -77,14 +75,14 @@ public class TestPointValues extends LuceneTestCase {Document doc = new Document();doc.add(new BinaryPoint("dim", new byte[4]));w.addDocument(doc);- doc = new Document();- doc.add(new BinaryPoint("dim", new byte[4], new byte[4]));- try {- w.addDocument(doc);- } catch (IllegalArgumentException iae) {- // expected- assertEquals("cannot change point dimension count from 1 to 2 for field=\"dim\"", iae.getMessage());- }++ Document doc2 = new Document();+ doc2.add(new BinaryPoint("dim", new byte[4], new byte[4]));+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ w.addDocument(doc2);+ });+ assertEquals("cannot change point dimension count from 1 to 2 for field=\"dim\"", expected.getMessage());+w.close();dir.close();}@@ -97,14 +95,14 @@ public class TestPointValues extends LuceneTestCase {doc.add(new BinaryPoint("dim", new byte[4]));w.addDocument(doc);w.commit();- doc = new Document();- doc.add(new BinaryPoint("dim", new byte[4], new byte[4]));- try {- w.addDocument(doc);- } catch (IllegalArgumentException iae) {- // expected- assertEquals("cannot change point dimension count from 1 to 2 for field=\"dim\"", iae.getMessage());- }++ Document doc2 = new Document();+ doc2.add(new BinaryPoint("dim", new byte[4], new byte[4]));+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ w.addDocument(doc2);+ });+ assertEquals("cannot change point dimension count from 1 to 2 for field=\"dim\"", expected.getMessage());+w.close();dir.close();}@@ -118,16 +116,16 @@ public class TestPointValues extends LuceneTestCase {w.addDocument(doc);w.close();iwc = new IndexWriterConfig(new MockAnalyzer(random()));- w = new IndexWriter(dir, iwc);- doc = new Document();- doc.add(new BinaryPoint("dim", new byte[4], new byte[4]));- try {- w.addDocument(doc);- } catch (IllegalArgumentException iae) {- // expected- assertEquals("cannot change point dimension count from 1 to 2 for field=\"dim\"", iae.getMessage());- }- w.close();++ IndexWriter w2 = new IndexWriter(dir, iwc);+ Document doc2 = new Document();+ doc2.add(new BinaryPoint("dim", new byte[4], new byte[4]));+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ w2.addDocument(doc2);+ });+ assertEquals("cannot change point dimension count from 1 to 2 for field=\"dim\"", expected.getMessage());++ w2.close();dir.close();}@@ -141,17 +139,16 @@ public class TestPointValues extends LuceneTestCase {w.close();Directory dir2 = newDirectory();- iwc = new IndexWriterConfig(new MockAnalyzer(random()));- w = new IndexWriter(dir2, iwc);+ IndexWriter w2 = new IndexWriter(dir2, new IndexWriterConfig(new MockAnalyzer(random())));doc = new Document();doc.add(new BinaryPoint("dim", new byte[4], new byte[4]));- w.addDocument(doc);- try {- w.addIndexes(new Directory[] {dir});- } catch (IllegalArgumentException iae) {- assertEquals("cannot change point dimension count from 2 to 1 for field=\"dim\"", iae.getMessage());- }- IOUtils.close(w, dir, dir2);+ w2.addDocument(doc);+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ w2.addIndexes(new Directory[] {dir});+ });+ assertEquals("cannot change point dimension count from 2 to 1 for field=\"dim\"", expected.getMessage());++ IOUtils.close(w2, dir, dir2);}public void testIllegalDimChangeViaAddIndexesCodecReader() throws Exception {@@ -164,18 +161,17 @@ public class TestPointValues extends LuceneTestCase {w.close();Directory dir2 = newDirectory();- iwc = new IndexWriterConfig(new MockAnalyzer(random()));- w = new IndexWriter(dir2, iwc);+ IndexWriter w2 = new IndexWriter(dir2, new IndexWriterConfig(new MockAnalyzer(random())));doc = new Document();doc.add(new BinaryPoint("dim", new byte[4], new byte[4]));- w.addDocument(doc);+ w2.addDocument(doc);DirectoryReader r = DirectoryReader.open(dir);- try {- w.addIndexes(new CodecReader[] {getOnlySegmentReader(r)});- } catch (IllegalArgumentException iae) {- assertEquals("cannot change point dimension count from 2 to 1 for field=\"dim\"", iae.getMessage());- }- IOUtils.close(r, w, dir, dir2);+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ w2.addIndexes(new CodecReader[] {getOnlySegmentReader(r)});+ });+ assertEquals("cannot change point dimension count from 2 to 1 for field=\"dim\"", expected.getMessage());++ IOUtils.close(r, w2, dir, dir2);}public void testIllegalDimChangeViaAddIndexesSlowCodecReader() throws Exception {@@ -189,17 +185,17 @@ public class TestPointValues extends LuceneTestCase {Directory dir2 = newDirectory();iwc = new IndexWriterConfig(new MockAnalyzer(random()));- w = new IndexWriter(dir2, iwc);+ IndexWriter w2 = new IndexWriter(dir2, iwc);doc = new Document();doc.add(new BinaryPoint("dim", new byte[4], new byte[4]));- w.addDocument(doc);+ w2.addDocument(doc);DirectoryReader r = DirectoryReader.open(dir);- try {- TestUtil.addIndexesSlowly(w, r);- } catch (IllegalArgumentException iae) {- assertEquals("cannot change point dimension count from 2 to 1 for field=\"dim\"", iae.getMessage());- }- IOUtils.close(r, w, dir, dir2);+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ TestUtil.addIndexesSlowly(w2, r);+ });+ assertEquals("cannot change point dimension count from 2 to 1 for field=\"dim\"", expected.getMessage());++ IOUtils.close(r, w2, dir, dir2);}public void testIllegalNumBytesChangeOneDoc() throws Exception {@@ -209,12 +205,11 @@ public class TestPointValues extends LuceneTestCase {Document doc = new Document();doc.add(new BinaryPoint("dim", new byte[4]));doc.add(new BinaryPoint("dim", new byte[6]));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);- } catch (IllegalArgumentException iae) {- // expected- assertEquals("cannot change point numBytes from 4 to 6 for field=\"dim\"", iae.getMessage());- }+ });+ assertEquals("cannot change point numBytes from 4 to 6 for field=\"dim\"", expected.getMessage());+w.close();dir.close();}@@ -226,14 +221,14 @@ public class TestPointValues extends LuceneTestCase {Document doc = new Document();doc.add(new BinaryPoint("dim", new byte[4]));w.addDocument(doc);- doc = new Document();- doc.add(new BinaryPoint("dim", new byte[6]));- try {- w.addDocument(doc);- } catch (IllegalArgumentException iae) {- // expected- assertEquals("cannot change point numBytes from 4 to 6 for field=\"dim\"", iae.getMessage());- }++ Document doc2 = new Document();+ doc2.add(new BinaryPoint("dim", new byte[6]));+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ w.addDocument(doc2);+ });+ assertEquals("cannot change point numBytes from 4 to 6 for field=\"dim\"", expected.getMessage());+w.close();dir.close();}@@ -246,14 +241,14 @@ public class TestPointValues extends LuceneTestCase {doc.add(new BinaryPoint("dim", new byte[4]));w.addDocument(doc);w.commit();- doc = new Document();- doc.add(new BinaryPoint("dim", new byte[6]));- try {- w.addDocument(doc);- } catch (IllegalArgumentException iae) {- // expected- assertEquals("cannot change point numBytes from 4 to 6 for field=\"dim\"", iae.getMessage());- }++ Document doc2 = new Document();+ doc2.add(new BinaryPoint("dim", new byte[6]));+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ w.addDocument(doc2);+ });+ assertEquals("cannot change point numBytes from 4 to 6 for field=\"dim\"", expected.getMessage());+w.close();dir.close();}@@ -266,17 +261,18 @@ public class TestPointValues extends LuceneTestCase {doc.add(new BinaryPoint("dim", new byte[4]));w.addDocument(doc);w.close();+iwc = new IndexWriterConfig(new MockAnalyzer(random()));- w = new IndexWriter(dir, iwc);- doc = new Document();- doc.add(new BinaryPoint("dim", new byte[6]));- try {- w.addDocument(doc);- } catch (IllegalArgumentException iae) {- // expected- assertEquals("cannot change point numBytes from 4 to 6 for field=\"dim\"", iae.getMessage());- }- w.close();+ IndexWriter w2 = new IndexWriter(dir, iwc);+ Document doc2 = new Document();+ doc2.add(new BinaryPoint("dim", new byte[6]));++ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ w2.addDocument(doc2);+ });+ assertEquals("cannot change point numBytes from 4 to 6 for field=\"dim\"", expected.getMessage());++ w2.close();dir.close();}@@ -291,16 +287,16 @@ public class TestPointValues extends LuceneTestCase {Directory dir2 = newDirectory();iwc = new IndexWriterConfig(new MockAnalyzer(random()));- w = new IndexWriter(dir2, iwc);+ IndexWriter w2 = new IndexWriter(dir2, iwc);doc = new Document();doc.add(new BinaryPoint("dim", new byte[6]));- w.addDocument(doc);- try {- w.addIndexes(new Directory[] {dir});- } catch (IllegalArgumentException iae) {- assertEquals("cannot change point numBytes from 6 to 4 for field=\"dim\"", iae.getMessage());- }- IOUtils.close(w, dir, dir2);+ w2.addDocument(doc);+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ w2.addIndexes(new Directory[] {dir});+ });+ assertEquals("cannot change point numBytes from 6 to 4 for field=\"dim\"", expected.getMessage());++ IOUtils.close(w2, dir, dir2);}public void testIllegalNumBytesChangeViaAddIndexesCodecReader() throws Exception {@@ -314,17 +310,17 @@ public class TestPointValues extends LuceneTestCase {Directory dir2 = newDirectory();iwc = new IndexWriterConfig(new MockAnalyzer(random()));- w = new IndexWriter(dir2, iwc);+ IndexWriter w2 = new IndexWriter(dir2, iwc);doc = new Document();doc.add(new BinaryPoint("dim", new byte[6]));- w.addDocument(doc);+ w2.addDocument(doc);DirectoryReader r = DirectoryReader.open(dir);- try {- w.addIndexes(new CodecReader[] {getOnlySegmentReader(r)});- } catch (IllegalArgumentException iae) {- assertEquals("cannot change point numBytes from 6 to 4 for field=\"dim\"", iae.getMessage());- }- IOUtils.close(r, w, dir, dir2);+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ w2.addIndexes(new CodecReader[] {getOnlySegmentReader(r)});+ });+ assertEquals("cannot change point numBytes from 6 to 4 for field=\"dim\"", expected.getMessage());++ IOUtils.close(r, w2, dir, dir2);}public void testIllegalNumBytesChangeViaAddIndexesSlowCodecReader() throws Exception {@@ -338,17 +334,17 @@ public class TestPointValues extends LuceneTestCase {Directory dir2 = newDirectory();iwc = new IndexWriterConfig(new MockAnalyzer(random()));- w = new IndexWriter(dir2, iwc);+ IndexWriter w2 = new IndexWriter(dir2, iwc);doc = new Document();doc.add(new BinaryPoint("dim", new byte[6]));- w.addDocument(doc);+ w2.addDocument(doc);DirectoryReader r = DirectoryReader.open(dir);- try {- TestUtil.addIndexesSlowly(w, r);- } catch (IllegalArgumentException iae) {- assertEquals("cannot change point numBytes from 6 to 4 for field=\"dim\"", iae.getMessage());- }- IOUtils.close(r, w, dir, dir2);+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ TestUtil.addIndexesSlowly(w2, r);+ });+ assertEquals("cannot change point numBytes from 6 to 4 for field=\"dim\"", expected.getMessage());++ IOUtils.close(r, w2, dir, dir2);}public void testIllegalTooManyBytes() throws Exception {@@ -357,15 +353,13 @@ public class TestPointValues extends LuceneTestCase {IndexWriter w = new IndexWriter(dir, iwc);Document doc = new Document();doc.add(new BinaryPoint("dim", new byte[PointValues.MAX_NUM_BYTES+1]));- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }- doc = new Document();- doc.add(new IntPoint("dim", 17));- w.addDocument(doc);+ });++ Document doc2 = new Document();+ doc2.add(new IntPoint("dim", 17));+ w.addDocument(doc2);w.close();dir.close();}@@ -380,15 +374,13 @@ public class TestPointValues extends LuceneTestCase {values[i] = new byte[4];}doc.add(new BinaryPoint("dim", values));- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }- doc = new Document();- doc.add(new IntPoint("dim", 17));- w.addDocument(doc);+ });++ Document doc2 = new Document();+ doc2.add(new IntPoint("dim", 17));+ w.addDocument(doc2);w.close();dir.close();}@@ -441,69 +433,49 @@ public class TestPointValues extends LuceneTestCase {public void testInvalidIntPointUsage() throws Exception {IntPoint field = new IntPoint("field", 17, 42);- try {- field.setIntValue(14);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // good- }- try {+ expectThrows(IllegalArgumentException.class, () -> {+ field.setIntValue(14);+ });++ expectThrows(IllegalStateException.class, () -> {field.numericValue();- fail("did not hit exception");- } catch (IllegalStateException ise) {- // good- }+ });}public void testInvalidLongPointUsage() throws Exception {LongPoint field = new LongPoint("field", 17, 42);- try {++ expectThrows(IllegalArgumentException.class, () -> {field.setLongValue(14);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // good- }+ });- try {+ expectThrows(IllegalStateException.class, () -> {field.numericValue();- fail("did not hit exception");- } catch (IllegalStateException ise) {- // good- }+ });}public void testInvalidFloatPointUsage() throws Exception {FloatPoint field = new FloatPoint("field", 17, 42);- try {++ expectThrows(IllegalArgumentException.class, () -> {field.setFloatValue(14);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // good- }+ });- try {+ expectThrows(IllegalStateException.class, () -> {field.numericValue();- fail("did not hit exception");- } catch (IllegalStateException ise) {- // good- }+ });}public void testInvalidDoublePointUsage() throws Exception {DoublePoint field = new DoublePoint("field", 17, 42);- try {++ expectThrows(IllegalArgumentException.class, () -> {field.setDoubleValue(14);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // good- }+ });- try {+ expectThrows(IllegalStateException.class, () -> {field.numericValue();- fail("did not hit exception");- } catch (IllegalStateException ise) {- // good- }+ });}}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.java b/lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.javaindex bf01c8ad72d..aff0bd9f06f 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestPostingsOffsets.java@@ -402,48 +402,36 @@ public class TestPostingsOffsets extends LuceneTestCase {// NOTE: the next two tests aren't that good as we need an EvilToken...public void testNegativeOffsets() throws Exception {- try {+ expectThrows(IllegalArgumentException.class, () -> {checkTokens(new Token[] {makeToken("foo", 1, -1, -1)});- fail();- } catch (IllegalArgumentException expected) {- //expected- }+ });}public void testIllegalOffsets() throws Exception {- try {+ expectThrows(IllegalArgumentException.class, () -> {checkTokens(new Token[] {makeToken("foo", 1, 1, 0)});- fail();- } catch (IllegalArgumentException expected) {- //expected- }+ });}public void testIllegalOffsetsAcrossFieldInstances() throws Exception {- try {+ expectThrows(IllegalArgumentException.class, () -> {checkTokens(new Token[] { makeToken("use", 1, 150, 160) },new Token[] { makeToken("use", 1, 50, 60) });- fail();- } catch (IllegalArgumentException expected) {- //expected- }+ });}public void testBackwardsOffsets() throws Exception {- try {+ expectThrows(IllegalArgumentException.class, () -> {checkTokens(new Token[] {makeToken("foo", 1, 0, 3),makeToken("foo", 1, 4, 7),makeToken("foo", 0, 3, 6)});- fail();- } catch (IllegalArgumentException expected) {- // expected- }+ });}public void testStackedTokens() throws Exception {@@ -471,14 +459,14 @@ public class TestPostingsOffsets extends LuceneTestCase {// add good documentDocument doc = new Document();iw.addDocument(doc);- try {+ expectThrows(IllegalArgumentException.class, () -> {FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);ft.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS);doc.add(new Field("foo", "bar", ft));doc.add(new Field("foo", "bar", ft));iw.addDocument(doc);- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {}+ });+ iw.commit();iw.close();// make sure we see our good docdiff --git a/lucene/core/src/test/org/apache/lucene/index/TestSegmentReader.java b/lucene/core/src/test/org/apache/lucene/index/TestSegmentReader.javaindex e43bc0e7c42..f008afe7a79 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestSegmentReader.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestSegmentReader.java@@ -204,25 +204,21 @@ public class TestSegmentReader extends LuceneTestCase {public void testOutOfBoundsAccess() throws IOException {int numDocs = reader.maxDoc();- try {++ expectThrows(IndexOutOfBoundsException.class, () -> {reader.document(-1);- fail();- } catch (IndexOutOfBoundsException expected) {}+ });- try {+ expectThrows(IndexOutOfBoundsException.class, () -> {reader.getTermVectors(-1);- fail();- } catch (IndexOutOfBoundsException expected) {}+ });- try {+ expectThrows(IndexOutOfBoundsException.class, () -> {reader.document(numDocs);- fail();- } catch (IndexOutOfBoundsException expected) {}+ });- try {+ expectThrows(IndexOutOfBoundsException.class, () -> {reader.getTermVectors(numDocs);- fail();- } catch (IndexOutOfBoundsException expected) {}-+ });}}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestSnapshotDeletionPolicy.java b/lucene/core/src/test/org/apache/lucene/index/TestSnapshotDeletionPolicy.javaindex ad87ed82012..c72e26d6bee 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestSnapshotDeletionPolicy.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestSnapshotDeletionPolicy.java@@ -113,13 +113,10 @@ public class TestSnapshotDeletionPolicy extends LuceneTestCase {.setMaxBufferedDocs(2));// Verify we catch misuse:- try {+ expectThrows(IllegalStateException.class, () -> {dp.snapshot();- fail("did not hit exception");- } catch(IllegalStateException ise) {- // expected- }- dp = (SnapshotDeletionPolicy) writer.getConfig().getIndexDeletionPolicy();+ });+writer.commit();final Thread t = new Thread() {diff --git a/lucene/core/src/test/org/apache/lucene/index/TestTermVectorsReader.java b/lucene/core/src/test/org/apache/lucene/index/TestTermVectorsReader.javaindex fad075533d6..4b2a06095a6 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestTermVectorsReader.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestTermVectorsReader.java@@ -336,7 +336,7 @@ public class TestTermVectorsReader extends LuceneTestCase {reader.close();}- public void testIllegalIndexableField() throws Exception {+ public void testIllegalPayloadsWithoutPositions() throws Exception {Directory dir = newDirectory();MockAnalyzer a = new MockAnalyzer(random());a.setEnableChecks(false);@@ -346,116 +346,149 @@ public class TestTermVectorsReader extends LuceneTestCase {ft.setStoreTermVectorPayloads(true);Document doc = new Document();doc.add(new Field("field", "value", ft));- try {- w.addDocument(doc);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // Expected- assertEquals("cannot index term vector payloads without term vector positions (field=\"field\")", iae.getMessage());- }- ft = new FieldType(TextField.TYPE_NOT_STORED);+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ w.addDocument(doc);+ });+ assertEquals("cannot index term vector payloads without term vector positions (field=\"field\")", expected.getMessage());++ w.close();+ dir.close();+ }++ public void testIllegalOffsetsWithoutVectors() throws Exception {+ Directory dir = newDirectory();+ MockAnalyzer a = new MockAnalyzer(random());+ a.setEnableChecks(false);+ RandomIndexWriter w = new RandomIndexWriter(random(), dir, a);+ FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);ft.setStoreTermVectors(false);ft.setStoreTermVectorOffsets(true);- doc = new Document();+ Document doc = new Document();doc.add(new Field("field", "value", ft));- try {++ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // Expected- assertEquals("cannot index term vector offsets when term vectors are not indexed (field=\"field\")", iae.getMessage());- }+ });+ assertEquals("cannot index term vector offsets when term vectors are not indexed (field=\"field\")", expected.getMessage());++ w.close();+ dir.close();+ }- ft = new FieldType(TextField.TYPE_NOT_STORED);+ public void testIllegalPositionsWithoutVectors() throws Exception {+ Directory dir = newDirectory();+ MockAnalyzer a = new MockAnalyzer(random());+ a.setEnableChecks(false);+ RandomIndexWriter w = new RandomIndexWriter(random(), dir, a);+ FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);ft.setStoreTermVectors(false);ft.setStoreTermVectorPositions(true);- doc = new Document();+ Document doc = new Document();doc.add(new Field("field", "value", ft));- try {- w.addDocument(doc);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // Expected- assertEquals("cannot index term vector positions when term vectors are not indexed (field=\"field\")", iae.getMessage());- }- ft = new FieldType(TextField.TYPE_NOT_STORED);- ft.setStoreTermVectors(false);- ft.setStoreTermVectorPayloads(true);- doc = new Document();- doc.add(new Field("field", "value", ft));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // Expected- assertEquals("cannot index term vector payloads when term vectors are not indexed (field=\"field\")", iae.getMessage());- }+ });+ assertEquals("cannot index term vector positions when term vectors are not indexed (field=\"field\")", expected.getMessage());++ w.close();+ dir.close();+ }- ft = new FieldType(TextField.TYPE_NOT_STORED);- ft.setStoreTermVectors(true);+ public void testIllegalVectorPayloadsWithoutVectors() throws Exception {+ Directory dir = newDirectory();+ MockAnalyzer a = new MockAnalyzer(random());+ a.setEnableChecks(false);+ RandomIndexWriter w = new RandomIndexWriter(random(), dir, a);+ FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);+ ft.setStoreTermVectors(false);ft.setStoreTermVectorPayloads(true);- doc = new Document();+ Document doc = new Document();doc.add(new Field("field", "value", ft));- try {++ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // Expected- assertEquals("cannot index term vector payloads without term vector positions (field=\"field\")", iae.getMessage());- }+ });+ assertEquals("cannot index term vector payloads when term vectors are not indexed (field=\"field\")", expected.getMessage());++ w.close();+ dir.close();+ }- ft = new FieldType(StoredField.TYPE);+ public void testIllegalVectorsWithoutIndexed() throws Exception {+ Directory dir = newDirectory();+ MockAnalyzer a = new MockAnalyzer(random());+ a.setEnableChecks(false);+ RandomIndexWriter w = new RandomIndexWriter(random(), dir, a);+ FieldType ft = new FieldType(StoredField.TYPE);ft.setStoreTermVectors(true);- doc = new Document();+ Document doc = new Document();doc.add(new Field("field", "value", ft));- try {++ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // Expected- assertEquals("cannot store term vectors for a field that is not indexed (field=\"field\")", iae.getMessage());- }+ });+ assertEquals("cannot store term vectors for a field that is not indexed (field=\"field\")", expected.getMessage());++ w.close();+ dir.close();+ }- ft = new FieldType(StoredField.TYPE);+ public void testIllegalVectorPositionsWithoutIndexed() throws Exception {+ Directory dir = newDirectory();+ MockAnalyzer a = new MockAnalyzer(random());+ a.setEnableChecks(false);+ RandomIndexWriter w = new RandomIndexWriter(random(), dir, a);+ FieldType ft = new FieldType(StoredField.TYPE);ft.setStoreTermVectorPositions(true);- doc = new Document();+ Document doc = new Document();doc.add(new Field("field", "value", ft));- try {++ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // Expected- assertEquals("cannot store term vector positions for a field that is not indexed (field=\"field\")", iae.getMessage());- }+ });+ assertEquals("cannot store term vector positions for a field that is not indexed (field=\"field\")", expected.getMessage());++ w.close();+ dir.close();+ }- ft = new FieldType(StoredField.TYPE);+ public void testIllegalVectorOffsetsWithoutIndexed() throws Exception {+ Directory dir = newDirectory();+ MockAnalyzer a = new MockAnalyzer(random());+ a.setEnableChecks(false);+ RandomIndexWriter w = new RandomIndexWriter(random(), dir, a);+ FieldType ft = new FieldType(StoredField.TYPE);ft.setStoreTermVectorOffsets(true);- doc = new Document();+ Document doc = new Document();doc.add(new Field("field", "value", ft));- try {++ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // Expected- assertEquals("cannot store term vector offsets for a field that is not indexed (field=\"field\")", iae.getMessage());- }-- ft = new FieldType(StoredField.TYPE);+ });+ assertEquals("cannot store term vector offsets for a field that is not indexed (field=\"field\")", expected.getMessage());++ w.close();+ dir.close();+ }++ public void testIllegalVectorPayloadsWithoutIndexed() throws Exception {+ Directory dir = newDirectory();+ MockAnalyzer a = new MockAnalyzer(random());+ a.setEnableChecks(false);+ RandomIndexWriter w = new RandomIndexWriter(random(), dir, a);+ FieldType ft = new FieldType(StoredField.TYPE);ft.setStoreTermVectorPayloads(true);- doc = new Document();+ Document doc = new Document();doc.add(new Field("field", "value", ft));- try {++ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // Expected- assertEquals("cannot store term vector payloads for a field that is not indexed (field=\"field\")", iae.getMessage());- }+ });+ assertEquals("cannot store term vector payloads for a field that is not indexed (field=\"field\")", expected.getMessage());w.close();-dir.close();}}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestTermVectorsWriter.java b/lucene/core/src/test/org/apache/lucene/index/TestTermVectorsWriter.javaindex f1ce915dfa5..11f1503405b 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestTermVectorsWriter.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestTermVectorsWriter.java@@ -635,13 +635,11 @@ public class TestTermVectorsWriter extends LuceneTestCase {doc.add(new Field("field", "value2", ft2));// ensure broken doc hits exception- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {iw.addDocument(doc);- fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- assertNotNull(iae.getMessage());- assertTrue(iae.getMessage().startsWith("all instances of a given field name must have the same term vectors settings"));- }+ });+ assertNotNull(expected.getMessage());+ assertTrue(expected.getMessage().startsWith("all instances of a given field name must have the same term vectors settings"));// ensure good docs are still okIndexReader ir = iw.getReader();@@ -665,12 +663,11 @@ public class TestTermVectorsWriter extends LuceneTestCase {ft.setStoreTermVectors(true);ft.freeze();doc.add(new Field("field", "value", ft));- try {++ expectThrows(IllegalArgumentException.class, () -> {iw.addDocument(doc);- fail("should have hit exc");- } catch (IllegalArgumentException iae) {- // expected- }+ });+IndexReader r = DirectoryReader.open(iw);// Make sure the exc didn't lose our first document:diff --git a/lucene/core/src/test/org/apache/lucene/index/TestTieredMergePolicy.java b/lucene/core/src/test/org/apache/lucene/index/TestTieredMergePolicy.javaindex 1c83e06d1ab..c8a87d3793e 100644--- a/lucene/core/src/test/org/apache/lucene/index/TestTieredMergePolicy.java+++ b/lucene/core/src/test/org/apache/lucene/index/TestTieredMergePolicy.java@@ -170,12 +170,9 @@ public class TestTieredMergePolicy extends BaseMergePolicyTestCase {tmp.setMaxMergedSegmentMB(Long.MAX_VALUE/1024/1024.);assertEquals(Long.MAX_VALUE/1024/1024., tmp.getMaxMergedSegmentMB(), EPSILON*Long.MAX_VALUE);- try {+ expectThrows(IllegalArgumentException.class, () -> {tmp.setMaxMergedSegmentMB(-2.0);- fail("Didn't throw IllegalArgumentException");- } catch (IllegalArgumentException iae) {- // pass- }+ });tmp.setFloorSegmentMB(2.0);assertEquals(2.0, tmp.getFloorSegmentMB(), EPSILON);@@ -186,12 +183,9 @@ public class TestTieredMergePolicy extends BaseMergePolicyTestCase {tmp.setFloorSegmentMB(Long.MAX_VALUE/1024/1024.);assertEquals(Long.MAX_VALUE/1024/1024., tmp.getFloorSegmentMB(), EPSILON*Long.MAX_VALUE);- try {+ expectThrows(IllegalArgumentException.class, () -> {tmp.setFloorSegmentMB(-2.0);- fail("Didn't throw IllegalArgumentException");- } catch (IllegalArgumentException iae) {- // pass- }+ });tmp.setMaxCFSSegmentSizeMB(2.0);assertEquals(2.0, tmp.getMaxCFSSegmentSizeMB(), EPSILON);@@ -202,12 +196,9 @@ public class TestTieredMergePolicy extends BaseMergePolicyTestCase {tmp.setMaxCFSSegmentSizeMB(Long.MAX_VALUE/1024/1024.);assertEquals(Long.MAX_VALUE/1024/1024., tmp.getMaxCFSSegmentSizeMB(), EPSILON*Long.MAX_VALUE);- try {+ expectThrows(IllegalArgumentException.class, () -> {tmp.setMaxCFSSegmentSizeMB(-2.0);- fail("Didn't throw IllegalArgumentException");- } catch (IllegalArgumentException iae) {- // pass- }+ });// TODO: Add more checks for other non-double setters!}diff --git a/lucene/core/src/test/org/apache/lucene/search/MultiCollectorTest.java b/lucene/core/src/test/org/apache/lucene/search/MultiCollectorTest.javaindex fe6374120de..de97954cfaa 100644--- a/lucene/core/src/test/org/apache/lucene/search/MultiCollectorTest.java+++ b/lucene/core/src/test/org/apache/lucene/search/MultiCollectorTest.java@@ -59,12 +59,9 @@ public class MultiCollectorTest extends LuceneTestCase {@Testpublic void testNullCollectors() throws Exception {// Tests that the collector rejects all null collectors.- try {+ expectThrows(IllegalArgumentException.class, () -> {MultiCollector.wrap(null, null);- fail("only null collectors should not be supported");- } catch (IllegalArgumentException e) {- // expected- }+ });// Tests that the collector handles some null collectors well. If it// doesn't, an NPE would be thrown.@@ -141,12 +138,9 @@ public class MultiCollectorTest extends LuceneTestCase {final LeafReaderContext ctx = reader.leaves().get(0);- try {+ expectThrows(AssertionError.class, () -> {collector(false, ScoreCachingWrappingScorer.class).getLeafCollector(ctx).setScorer(new FakeScorer());- fail("The collector was configured to expect a ScoreCachingWrappingScorer and did not fail when pass in a FakeScorer");- } catch (AssertionError e) {- // expected- }+ });// no collector needs scores => no cachingCollector c1 = collector(false, FakeScorer.class);diff --git a/lucene/core/src/test/org/apache/lucene/search/TestBooleanQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestBooleanQuery.javaindex 5e16bcb2f66..397035577d8 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestBooleanQuery.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestBooleanQuery.java@@ -189,12 +189,9 @@ public class TestBooleanQuery extends LuceneTestCase {}public void testException() {- try {+ expectThrows(IllegalArgumentException.class, () -> {BooleanQuery.setMaxClauseCount(0);- fail();- } catch (IllegalArgumentException e) {- // okay- }+ });}// LUCENE-1630diff --git a/lucene/core/src/test/org/apache/lucene/search/TestCachingCollector.java b/lucene/core/src/test/org/apache/lucene/search/TestCachingCollector.javaindex 18869196f8f..89304bac2cb 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestCachingCollector.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestCachingCollector.java@@ -99,12 +99,9 @@ public class TestCachingCollector extends LuceneTestCase {assertFalse("CachingCollector should not be cached due to low memory limit", cc.isCached());- try {+ expectThrows(IllegalStateException.class, () -> {cc.replay(new NoOpCollector());- fail("replay should fail if CachingCollector is not cached");- } catch (IllegalStateException e) {- // expected- }+ });}public void testCachedArraysAllocation() throws Exception {diff --git a/lucene/core/src/test/org/apache/lucene/search/TestControlledRealTimeReopenThread.java b/lucene/core/src/test/org/apache/lucene/search/TestControlledRealTimeReopenThread.javaindex 2ed7c433a89..8217eb1c132 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestControlledRealTimeReopenThread.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestControlledRealTimeReopenThread.java@@ -422,12 +422,10 @@ public class TestControlledRealTimeReopenThread extends ThreadedIndexingAndSearc}};- try {+ expectThrows(IllegalStateException.class, () -> {new SearcherManager(w.w, false, false, theEvilOne);- fail("didn't hit expected exception");- } catch (IllegalStateException ise) {- // expected- }+ });+w.close();other.close();dir.close();diff --git a/lucene/core/src/test/org/apache/lucene/search/TestFuzzyQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestFuzzyQuery.javaindex 7f36902b615..79dc157d883 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestFuzzyQuery.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestFuzzyQuery.java@@ -449,52 +449,39 @@ public class TestFuzzyQuery extends LuceneTestCase {assertEquals(1, hits.length);assertEquals("foobar", searcher.doc(hits[0].doc).get("field"));- try {- q = new FuzzyQuery(new Term("field", "t"), 3);- fail();- } catch (IllegalArgumentException expected) {- // expected- }-+ expectThrows(IllegalArgumentException.class, () -> {+ new FuzzyQuery(new Term("field", "t"), 3);+ });+reader.close();index.close();}public void testValidation() {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new FuzzyQuery(new Term("field", "foo"), -1, 0, 1, false);- fail("Expected error for illegal max edits value");- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("maxEdits"));- }+ });+ assertTrue(expected.getMessage().contains("maxEdits"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {new FuzzyQuery(new Term("field", "foo"), LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE + 1, 0, 1, false);- fail("Expected error for illegal max edits value");- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("maxEdits must be between"));- }+ });+ assertTrue(expected.getMessage().contains("maxEdits must be between"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {new FuzzyQuery(new Term("field", "foo"), 1, -1, 1, false);- fail("Expected error for illegal prefix length value");- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("prefixLength cannot be negative"));- }+ });+ assertTrue(expected.getMessage().contains("prefixLength cannot be negative"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {new FuzzyQuery(new Term("field", "foo"), 1, 0, -1, false);- fail("Expected error for illegal max expansions value");- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("maxExpansions must be positive"));- }+ });+ assertTrue(expected.getMessage().contains("maxExpansions must be positive"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {new FuzzyQuery(new Term("field", "foo"), 1, 0, -1, false);- fail("Expected error for illegal max expansions value");- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("maxExpansions must be positive"));- }+ });+ assertTrue(expected.getMessage().contains("maxExpansions must be positive"));}private void addDoc(String text, RandomIndexWriter writer) throws IOException {diff --git a/lucene/core/src/test/org/apache/lucene/search/TestIndexSearcher.java b/lucene/core/src/test/org/apache/lucene/search/TestIndexSearcher.javaindex c561d64d8e0..e7cdfcdd69b 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestIndexSearcher.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestIndexSearcher.java@@ -129,14 +129,11 @@ public class TestIndexSearcher extends LuceneTestCase {w.close();IndexSearcher s = new IndexSearcher(r);- try {+ expectThrows(IllegalArgumentException.class, () -> {s.searchAfter(new ScoreDoc(r.maxDoc(), 0.54f), new MatchAllDocsQuery(), 10);- fail("should have hit IllegalArgumentException when searchAfter exceeds maxDoc");- } catch (IllegalArgumentException e) {- // ok- } finally {- IOUtils.close(r, dir);- }+ });++ IOUtils.close(r, dir);}public void testCount() throws IOException {diff --git a/lucene/core/src/test/org/apache/lucene/search/TestMultiCollector.java b/lucene/core/src/test/org/apache/lucene/search/TestMultiCollector.javaindex 4ef54dac3d1..3b4e1bd5d3f 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestMultiCollector.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestMultiCollector.java@@ -152,12 +152,9 @@ public class TestMultiCollector extends LuceneTestCase {assertFalse(setScorerCalled1.get());assertTrue(setScorerCalled2.get());- try {+ expectThrows(CollectionTerminatedException.class, () -> {leafCollector.collect(1);- fail();- } catch (CollectionTerminatedException e) {- // expected- }+ });setScorerCalled1.set(false);setScorerCalled2.set(false);diff --git a/lucene/core/src/test/org/apache/lucene/search/TestMultiPhraseQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestMultiPhraseQuery.javaindex d2fec0e817f..5c81fed6d14 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestMultiPhraseQuery.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestMultiPhraseQuery.java@@ -125,13 +125,10 @@ public class TestMultiPhraseQuery extends LuceneTestCase {// foobar pizzaMultiPhraseQuery query4 = new MultiPhraseQuery();- try {+ expectThrows(IllegalArgumentException.class, () -> {query4.add(new Term("field1", "foo"));query4.add(new Term("field2", "foobar"));- fail();- } catch (IllegalArgumentException e) {- // okay, all terms must belong to the same field- }+ });writer.close();reader.close();@@ -571,12 +568,9 @@ public class TestMultiPhraseQuery extends LuceneTestCase {MultiPhraseQuery query = new MultiPhraseQuery();query.add(new Term("field", "two"));query.add(new Term("field", "one"));- try {+ expectThrows(IllegalArgumentException.class, () -> {query.setSlop(-2);- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- // expected exception- }+ });}}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestMultiTermQueryRewrites.java b/lucene/core/src/test/org/apache/lucene/search/TestMultiTermQueryRewrites.javaindex 3772d451302..458dd68d36f 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestMultiTermQueryRewrites.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestMultiTermQueryRewrites.java@@ -215,12 +215,12 @@ public class TestMultiTermQueryRewrites extends LuceneTestCase {final MultiTermQuery mtq = TermRangeQuery.newStringRange("data", "2", "7", true, true);mtq.setRewriteMethod(method);try {- multiSearcherDupls.rewrite(mtq);- fail("Should throw BooleanQuery.TooManyClauses");- } catch (BooleanQuery.TooManyClauses e) {+ BooleanQuery.TooManyClauses expected = expectThrows(BooleanQuery.TooManyClauses.class, () -> {+ multiSearcherDupls.rewrite(mtq);+ });// Maybe remove this assert in later versions, when internal API changes:assertEquals("Should throw BooleanQuery.TooManyClauses with a stacktrace containing checkMaxClauseCount()",- "checkMaxClauseCount", e.getStackTrace()[0].getMethodName());+ "checkMaxClauseCount", expected.getStackTrace()[0].getMethodName());} finally {BooleanQuery.setMaxClauseCount(savedMaxClauseCount);}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestPhraseQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestPhraseQuery.javaindex c9f8f9749e0..cf779034d81 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestPhraseQuery.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestPhraseQuery.java@@ -693,33 +693,24 @@ public class TestPhraseQuery extends LuceneTestCase {}public void testNegativeSlop() throws Exception {- try {+ expectThrows(IllegalArgumentException.class, () -> {new PhraseQuery(-2, "field", "two", "one");- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- // expected exception- }+ });}public void testNegativePosition() throws Exception {PhraseQuery.Builder builder = new PhraseQuery.Builder();- try {+ expectThrows(IllegalArgumentException.class, () -> {builder.add(new Term("field", "two"), -42);- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- // expected exception- }+ });}public void testBackwardPositions() throws Exception {PhraseQuery.Builder builder = new PhraseQuery.Builder();builder.add(new Term("field", "one"), 1);builder.add(new Term("field", "two"), 5);- try {+ expectThrows(IllegalArgumentException.class, () -> {builder.add(new Term("field", "three"), 4);- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- // expected exception- }+ });}}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestPointQueries.java b/lucene/core/src/test/org/apache/lucene/search/TestPointQueries.javaindex 3fca6819f30..5758546b7b0 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestPointQueries.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestPointQueries.java@@ -948,11 +948,10 @@ public class TestPointQueries extends LuceneTestCase {// no wrapping, else the exc might happen in executor thread:IndexSearcher s = new IndexSearcher(r);byte[][] point = new byte[2][];- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {s.count(new PointRangeQuery("value", point, new boolean[] {true, true}, point, new boolean[] {true, true}));- } catch (IllegalArgumentException iae) {- assertEquals("field=\"value\" was indexed with numDims=1 but this query has numDims=2", iae.getMessage());- }+ });+ assertEquals("field=\"value\" was indexed with numDims=1 but this query has numDims=2", expected.getMessage());IOUtils.close(r, w, dir);}@@ -972,11 +971,10 @@ public class TestPointQueries extends LuceneTestCase {IndexSearcher s = new IndexSearcher(r);byte[][] point = new byte[1][];point[0] = new byte[10];- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {s.count(new PointRangeQuery("value", point, new boolean[] {true}, point, new boolean[] {true}));- } catch (IllegalArgumentException iae) {- assertEquals("field=\"value\" was indexed with bytesPerDim=8 but this query has bytesPerDim=10", iae.getMessage());- }+ });+ assertEquals("field=\"value\" was indexed with bytesPerDim=8 but this query has bytesPerDim=10", expected.getMessage());IOUtils.close(r, w, dir);}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSearcherManager.java b/lucene/core/src/test/org/apache/lucene/search/TestSearcherManager.javaindex f33acf92c11..02419b8ff8d 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestSearcherManager.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestSearcherManager.java@@ -280,12 +280,9 @@ public class TestSearcherManager extends ThreadedIndexingAndSearchingTestCase {searcherManager.close();awaitClose.countDown();thread.join();- try {+ expectThrows(AlreadyClosedException.class, () -> {searcherManager.acquire();- fail("already closed");- } catch (AlreadyClosedException ex) {- // expected- }+ });assertFalse(success.get());assertTrue(triedReopen.get());assertNull("" + exc[0], exc[0]);@@ -325,12 +322,9 @@ public class TestSearcherManager extends ThreadedIndexingAndSearchingTestCase {acquire = sm.acquire();acquire.getIndexReader().decRef();sm.release(acquire);- try {+ expectThrows(IllegalStateException.class, () -> {sm.acquire();- fail("acquire should have thrown an IllegalStateException since we modified the refCount outside of the manager");- } catch (IllegalStateException ex) {- //- }+ });// sm.close(); -- already closedwriter.close();@@ -348,19 +342,16 @@ public class TestSearcherManager extends ThreadedIndexingAndSearchingTestCase {// this should succeed;sm.release(s);- try {- // this should fail+ // this should fail+ expectThrows(AlreadyClosedException.class, () -> {sm.acquire();- } catch (AlreadyClosedException e) {- // ok- }+ });- try {- // this should fail+ // this should fail+ expectThrows(AlreadyClosedException.class, () -> {sm.maybeRefresh();- } catch (AlreadyClosedException e) {- // ok- }+ });+dir.close();}@@ -405,16 +396,12 @@ public class TestSearcherManager extends ThreadedIndexingAndSearchingTestCase {}};- try {+ expectThrows(IllegalStateException.class, () -> {new SearcherManager(dir, theEvilOne);- } catch (IllegalStateException ise) {- // expected- }- try {+ });+ expectThrows(IllegalStateException.class, () -> {new SearcherManager(w.w, random.nextBoolean(), false, theEvilOne);- } catch (IllegalStateException ise) {- // expected- }+ });w.close();other.close();dir.close();diff --git a/lucene/core/src/test/org/apache/lucene/search/TestSynonymQuery.java b/lucene/core/src/test/org/apache/lucene/search/TestSynonymQuery.javaindex 95e98659887..bc0a2d071dd 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestSynonymQuery.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestSynonymQuery.java@@ -40,10 +40,9 @@ public class TestSynonymQuery extends LuceneTestCase {}public void testBogusParams() {- try {+ expectThrows(IllegalArgumentException.class, () -> {new SynonymQuery(new Term("field1", "a"), new Term("field2", "b"));- fail();- } catch (IllegalArgumentException expected) {}+ });}public void testToString() {diff --git a/lucene/core/src/test/org/apache/lucene/search/TestTermScorer.java b/lucene/core/src/test/org/apache/lucene/search/TestTermScorer.javaindex cadc3ce2cbb..30061b5ca1f 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestTermScorer.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestTermScorer.java@@ -185,15 +185,12 @@ public class TestTermScorer extends LuceneTestCase {IndexSearcher indexSearcher = new IndexSearcher(forbiddenNorms);Weight weight = indexSearcher.createNormalizedWeight(termQuery, true);- try {+ expectThrows(AssertionError.class, () -> {weight.scorer(forbiddenNorms.getContext()).iterator().nextDoc();- fail("Should load norms");- } catch (AssertionError e) {- // ok- }+ });- weight = indexSearcher.createNormalizedWeight(termQuery, false);+ Weight weight2 = indexSearcher.createNormalizedWeight(termQuery, false);// should not fail this time since norms are not necessary- weight.scorer(forbiddenNorms.getContext()).iterator().nextDoc();+ weight2.scorer(forbiddenNorms.getContext()).iterator().nextDoc();}}diff --git a/lucene/core/src/test/org/apache/lucene/search/TestTimeLimitingCollector.java b/lucene/core/src/test/org/apache/lucene/search/TestTimeLimitingCollector.javaindex b98de806c99..d26006cad0a 100644--- a/lucene/core/src/test/org/apache/lucene/search/TestTimeLimitingCollector.java+++ b/lucene/core/src/test/org/apache/lucene/search/TestTimeLimitingCollector.java@@ -181,18 +181,10 @@ public class TestTimeLimitingCollector extends LuceneTestCase {myHc.setSlowDown(SLOW_DOWN);Collector tlCollector = createTimedCollector(myHc, TIME_ALLOWED, greedy);- // search- TimeExceededException timeoutException = null;- try {+ // search: must get exception+ TimeExceededException timeoutException = expectThrows(TimeExceededException.class, () -> {search(tlCollector);- } catch (TimeExceededException x) {- timeoutException = x;- } catch (Exception e) {- assertTrue("Unexpected exception: "+e, false); //==fail- }-- // must get exception- assertNotNull( "Timeout expected!", timeoutException );+ });// greediness affect last doc collectedint exceptionDoc = timeoutException.getLastDocCollected();@@ -275,18 +267,13 @@ public class TestTimeLimitingCollector extends LuceneTestCase {public void testNoHits() throws IOException {MyHitCollector myHc = new MyHitCollector();Collector collector = createTimedCollector(myHc, -1, random().nextBoolean());- // search- TimeExceededException timeoutException = null;- try {+ // search: must get exception+ expectThrows(TimeExceededException.class, () -> {BooleanQuery.Builder booleanQuery = new BooleanQuery.Builder(); // won't match - we only test if we check timeout when collectors are pulledbooleanQuery.add(new TermQuery(new Term(FIELD_NAME, "one")), BooleanClause.Occur.MUST);booleanQuery.add(new TermQuery(new Term(FIELD_NAME, "blueberry")), BooleanClause.Occur.MUST);searcher.search(booleanQuery.build(), collector);- } catch (TimeExceededException x) {- timeoutException = x;- }- // must get exception- assertNotNull("Timeout expected!", timeoutException);+ });assertEquals(-1, myHc.getLastDocCollected());}diff --git a/lucene/core/src/test/org/apache/lucene/search/similarities/TestBM25Similarity.java b/lucene/core/src/test/org/apache/lucene/search/similarities/TestBM25Similarity.javaindex f65397188bf..dc434068258 100644--- a/lucene/core/src/test/org/apache/lucene/search/similarities/TestBM25Similarity.java+++ b/lucene/core/src/test/org/apache/lucene/search/similarities/TestBM25Similarity.java@@ -35,48 +35,41 @@ public class TestBM25Similarity extends LuceneTestCase {}public void testIllegalK1() {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new BM25Similarity(Float.POSITIVE_INFINITY, 0.75f);- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("illegal k1 value"));- }+ });+ assertTrue(expected.getMessage().contains("illegal k1 value"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {new BM25Similarity(-1, 0.75f);- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("illegal k1 value"));- }+ });+ assertTrue(expected.getMessage().contains("illegal k1 value"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {new BM25Similarity(Float.NaN, 0.75f);- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("illegal k1 value"));- }+ });+ assertTrue(expected.getMessage().contains("illegal k1 value"));}public void testIllegalB() {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new BM25Similarity(1.2f, 2f);- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("illegal b value"));- }+ });+ assertTrue(expected.getMessage().contains("illegal b value"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {new BM25Similarity(1.2f, -1f);- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("illegal b value"));- }+ });+ assertTrue(expected.getMessage().contains("illegal b value"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {new BM25Similarity(1.2f, Float.POSITIVE_INFINITY);- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("illegal b value"));- }+ });+ assertTrue(expected.getMessage().contains("illegal b value"));- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {new BM25Similarity(1.2f, Float.NaN);- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("illegal b value"));- }+ });+ assertTrue(expected.getMessage().contains("illegal b value"));}}diff --git a/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanNearQuery.java b/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanNearQuery.javaindex b010147c84e..fbc098c612f 100644--- a/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanNearQuery.java+++ b/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanNearQuery.java@@ -48,12 +48,10 @@ public class TestSpanNearQuery extends LuceneTestCase {public void testDifferentField() throws Exception {SpanTermQuery q1 = new SpanTermQuery(new Term("field1", "foo"));SpanTermQuery q2 = new SpanTermQuery(new Term("field2", "bar"));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new SpanNearQuery(new SpanQuery[] { q1, q2 }, 10, true);- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("must have same field"));- }+ });+ assertTrue(expected.getMessage().contains("must have same field"));}public void testNoPositions() throws IOException {@@ -70,12 +68,11 @@ public class TestSpanNearQuery extends LuceneTestCase {SpanTermQuery query = new SpanTermQuery(new Term("foo", "bar"));SpanTermQuery query2 = new SpanTermQuery(new Term("foo", "baz"));- try {+ IllegalStateException expected = expectThrows(IllegalStateException.class, () -> {is.search(new SpanNearQuery(new SpanQuery[] { query, query2 }, 10, true), 5);- fail("didn't get expected exception");- } catch (IllegalStateException expected) {- assertTrue(expected.getMessage().contains("was indexed without position data"));- }+ });+ assertTrue(expected.getMessage().contains("was indexed without position data"));+ir.close();dir.close();}@@ -83,18 +80,14 @@ public class TestSpanNearQuery extends LuceneTestCase {public void testBuilder() throws Exception {// Can't add subclauses from different fields- try {+ expectThrows(IllegalArgumentException.class, () -> {SpanNearQuery.newOrderedNearQuery("field1").addClause(new SpanTermQuery(new Term("field2", "term")));- fail("Expected an error when adding a clause with a different field");- }- catch (IllegalArgumentException e) {}+ });// Can't add gaps to unordered queries- try {+ expectThrows(IllegalArgumentException.class, () -> {SpanNearQuery.newUnorderedNearQuery("field1").addGap(1);- fail("Expected an error when adding a gap to an unordered query");- }- catch (IllegalArgumentException e) {}+ });}}diff --git a/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanNotQuery.java b/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanNotQuery.javaindex 79026bb1608..4ffb270d128 100644--- a/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanNotQuery.java+++ b/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanNotQuery.java@@ -48,12 +48,10 @@ public class TestSpanNotQuery extends LuceneTestCase {public void testDifferentField() throws Exception {SpanTermQuery q1 = new SpanTermQuery(new Term("field1", "foo"));SpanTermQuery q2 = new SpanTermQuery(new Term("field2", "bar"));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new SpanNotQuery(q1, q2);- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("must have same field"));- }+ });+ assertTrue(expected.getMessage().contains("must have same field"));}public void testNoPositions() throws IOException {@@ -70,12 +68,11 @@ public class TestSpanNotQuery extends LuceneTestCase {SpanTermQuery query = new SpanTermQuery(new Term("foo", "bar"));SpanTermQuery query2 = new SpanTermQuery(new Term("foo", "baz"));- try {+ IllegalStateException expected = expectThrows(IllegalStateException.class, () -> {is.search(new SpanNotQuery(query, query2), 5);- fail("didn't get expected exception");- } catch (IllegalStateException expected) {- assertTrue(expected.getMessage().contains("was indexed without position data"));- }+ });+ assertTrue(expected.getMessage().contains("was indexed without position data"));+ir.close();dir.close();}diff --git a/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanOrQuery.java b/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanOrQuery.javaindex 6f3c41f9269..b0fe485638a 100644--- a/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanOrQuery.java+++ b/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanOrQuery.java@@ -45,11 +45,9 @@ public class TestSpanOrQuery extends LuceneTestCase {public void testDifferentField() throws Exception {SpanTermQuery q1 = new SpanTermQuery(new Term("field1", "foo"));SpanTermQuery q2 = new SpanTermQuery(new Term("field2", "bar"));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new SpanOrQuery(q1, q2);- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("must have same field"));- }+ });+ assertTrue(expected.getMessage().contains("must have same field"));}}diff --git a/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanTermQuery.java b/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanTermQuery.javaindex 97951bf7f8e..a1498ceaa26 100644--- a/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanTermQuery.java+++ b/lucene/core/src/test/org/apache/lucene/search/spans/TestSpanTermQuery.java@@ -53,12 +53,11 @@ public class TestSpanTermQuery extends LuceneTestCase {IndexSearcher is = new IndexSearcher(ir);SpanTermQuery query = new SpanTermQuery(new Term("foo", "bar"));- try {+ IllegalStateException expected = expectThrows(IllegalStateException.class, () -> {is.search(query, 5);- fail("didn't get expected exception");- } catch (IllegalStateException expected) {- assertTrue(expected.getMessage().contains("was indexed without position data"));- }+ });+ assertTrue(expected.getMessage().contains("was indexed without position data"));+ir.close();dir.close();}diff --git a/lucene/core/src/test/org/apache/lucene/store/TestBufferedIndexInput.java b/lucene/core/src/test/org/apache/lucene/store/TestBufferedIndexInput.javaindex df81d8ff0aa..178d7927a77 100644--- a/lucene/core/src/test/org/apache/lucene/store/TestBufferedIndexInput.java+++ b/lucene/core/src/test/org/apache/lucene/store/TestBufferedIndexInput.java@@ -142,26 +142,24 @@ public class TestBufferedIndexInput extends LuceneTestCase {input.seek(pos);checkReadBytes(input, 10, pos);input.seek(pos);- try {+ // block read past end of file+ expectThrows(IOException.class, () -> {checkReadBytes(input, 11, pos);- fail("Block read past end of file");- } catch (IOException e) {- /* success */- }+ });+input.seek(pos);- try {++ // block read past end of file+ expectThrows(IOException.class, () -> {checkReadBytes(input, 50, pos);- fail("Block read past end of file");- } catch (IOException e) {- /* success */- }+ });+input.seek(pos);- try {++ // block read past end of file+ expectThrows(IOException.class, () -> {checkReadBytes(input, 100000, pos);- fail("Block read past end of file");- } catch (IOException e) {- /* success */- }+ });}// byten emulates a file - byten(n) returns the n'th byte in that file.diff --git a/lucene/core/src/test/org/apache/lucene/store/TestDirectory.java b/lucene/core/src/test/org/apache/lucene/store/TestDirectory.javaindex 99f9e0c2e8e..571119d5d75 100644--- a/lucene/core/src/test/org/apache/lucene/store/TestDirectory.java+++ b/lucene/core/src/test/org/apache/lucene/store/TestDirectory.java@@ -89,12 +89,9 @@ public class TestDirectory extends LuceneTestCase {Lock lock = dir.obtainLock(lockname);for (Directory other : dirs) {- try {+ expectThrows(LockObtainFailedException.class, () -> {other.obtainLock(lockname);- fail("didnt get exception");- } catch (LockObtainFailedException e) {- // OK- }+ });}lock.close();@@ -131,12 +128,9 @@ public class TestDirectory extends LuceneTestCase {IndexOutput out = fsDir.createOutput("afile", newIOContext(random()));out.close();assertTrue(slowFileExists(fsDir, "afile"));- try {+ expectThrows(IOException.class, () -> {new SimpleFSDirectory(path.resolve("afile"));- fail("did not hit expected exception");- } catch (IOException nsde) {- // Expected- }+ });} finally {fsDir.close();}diff --git a/lucene/core/src/test/org/apache/lucene/store/TestFileSwitchDirectory.java b/lucene/core/src/test/org/apache/lucene/store/TestFileSwitchDirectory.javaindex bdd3dfa69da..927c913cbc1 100644--- a/lucene/core/src/test/org/apache/lucene/store/TestFileSwitchDirectory.java+++ b/lucene/core/src/test/org/apache/lucene/store/TestFileSwitchDirectory.java@@ -101,12 +101,10 @@ public class TestFileSwitchDirectory extends BaseDirectoryTestCase {Path primDir = createTempDir("foo");Path secondDir = createTempDir("bar");Directory dir = newFSSwitchDirectory(primDir, secondDir, Collections.<String>emptySet());- try {+ expectThrows(IndexNotFoundException.class, () -> {DirectoryReader.open(dir);- fail("did not hit expected exception");- } catch (IndexNotFoundException nsde) {- // expected- }+ });+dir.close();}diff --git a/lucene/core/src/test/org/apache/lucene/store/TestMultiMMap.java b/lucene/core/src/test/org/apache/lucene/store/TestMultiMMap.javaindex 3b6ef22e456..76632cbbaf7 100644--- a/lucene/core/src/test/org/apache/lucene/store/TestMultiMMap.java+++ b/lucene/core/src/test/org/apache/lucene/store/TestMultiMMap.java@@ -59,24 +59,16 @@ public class TestMultiMMap extends BaseDirectoryTestCase {IndexInput two = one.clone();IndexInput three = two.clone(); // clone of cloneone.close();- try {+ expectThrows(AlreadyClosedException.class, () -> {one.readVInt();- fail("Must throw AlreadyClosedException");- } catch (AlreadyClosedException ignore) {- // pass- }- try {+ });+ expectThrows(AlreadyClosedException.class, () -> {two.readVInt();- fail("Must throw AlreadyClosedException");- } catch (AlreadyClosedException ignore) {- // pass- }- try {+ });+ expectThrows(AlreadyClosedException.class, () -> {three.readVInt();- fail("Must throw AlreadyClosedException");- } catch (AlreadyClosedException ignore) {- // pass- }+ });+two.close();three.close();// test double close of master:@@ -94,12 +86,9 @@ public class TestMultiMMap extends BaseDirectoryTestCase {IndexInput three = two.clone(); // clone of clonetwo.close();assertEquals(5, one.readVInt());- try {+ expectThrows(AlreadyClosedException.class, () -> {two.readVInt();- fail("Must throw AlreadyClosedException");- } catch (AlreadyClosedException ignore) {- // pass- }+ });assertEquals(5, three.readVInt());one.close();three.close();@@ -118,30 +107,19 @@ public class TestMultiMMap extends BaseDirectoryTestCase {IndexInput three = one.clone(); // clone of cloneIndexInput four = two.clone(); // clone of cloneslicer.close();- try {+ expectThrows(AlreadyClosedException.class, () -> {one.readInt();- fail("Must throw AlreadyClosedException");- } catch (AlreadyClosedException ignore) {- // pass- }- try {+ });+ expectThrows(AlreadyClosedException.class, () -> {two.readInt();- fail("Must throw AlreadyClosedException");- } catch (AlreadyClosedException ignore) {- // pass- }- try {+ });+ expectThrows(AlreadyClosedException.class, () -> {three.readInt();- fail("Must throw AlreadyClosedException");- } catch (AlreadyClosedException ignore) {- // pass- }- try {+ });+ expectThrows(AlreadyClosedException.class, () -> {four.readInt();- fail("Must throw AlreadyClosedException");- } catch (AlreadyClosedException ignore) {- // pass- }+ });+one.close();two.close();three.close();@@ -161,17 +139,14 @@ public class TestMultiMMap extends BaseDirectoryTestCase {IndexInput one = slicer.slice("first int", 0, 4);IndexInput two = slicer.slice("second int", 4, 4);one.close();- try {+ expectThrows(AlreadyClosedException.class, () -> {one.readInt();- fail("Must throw AlreadyClosedException");- } catch (AlreadyClosedException ignore) {- // pass- }+ });assertEquals(2, two.readInt());- // reopen a new slice "one":- one = slicer.slice("first int", 0, 4);- assertEquals(1, one.readInt());- one.close();+ // reopen a new slice "another":+ IndexInput another = slicer.slice("first int", 0, 4);+ assertEquals(1, another.readInt());+ another.close();two.close();slicer.close();mmapDir.close();diff --git a/lucene/core/src/test/org/apache/lucene/store/TestNativeFSLockFactory.java b/lucene/core/src/test/org/apache/lucene/store/TestNativeFSLockFactory.javaindex 4e62daf78dc..5d202bff9e3 100644--- a/lucene/core/src/test/org/apache/lucene/store/TestNativeFSLockFactory.java+++ b/lucene/core/src/test/org/apache/lucene/store/TestNativeFSLockFactory.java@@ -50,14 +50,11 @@ public class TestNativeFSLockFactory extends BaseLockFactoryTestCase {NativeFSLockFactory.NativeFSLock lock = (NativeFSLockFactory.NativeFSLock) dir.obtainLock("test.lock");lock.ensureValid();lock.lock.release();- try {+ expectThrows(AlreadyClosedException.class, () -> {lock.ensureValid();- fail("no exception");- } catch (AlreadyClosedException expected) {- // ok- } finally {- IOUtils.closeWhileHandlingException(lock);- }+ });++ IOUtils.closeWhileHandlingException(lock);dir.close();}@@ -67,14 +64,11 @@ public class TestNativeFSLockFactory extends BaseLockFactoryTestCase {NativeFSLockFactory.NativeFSLock lock = (NativeFSLockFactory.NativeFSLock) dir.obtainLock("test.lock");lock.ensureValid();lock.channel.close();- try {+ expectThrows(AlreadyClosedException.class, () -> {lock.ensureValid();- fail("no exception");- } catch (AlreadyClosedException expected) {- // ok- } finally {- IOUtils.closeWhileHandlingException(lock);- }+ });++ IOUtils.closeWhileHandlingException(lock);dir.close();}@@ -88,14 +82,11 @@ public class TestNativeFSLockFactory extends BaseLockFactoryTestCase {dir.deleteFile("test.lock");- try {+ expectThrows(IOException.class, () -> {lock.ensureValid();- fail("no exception");- } catch (IOException expected) {- // ok- } finally {- IOUtils.closeWhileHandlingException(lock);- }+ });++ IOUtils.closeWhileHandlingException(lock);}}}diff --git a/lucene/core/src/test/org/apache/lucene/store/TestRAMDirectory.java b/lucene/core/src/test/org/apache/lucene/store/TestRAMDirectory.javaindex c5d30666353..d4e8bfc2242 100644--- a/lucene/core/src/test/org/apache/lucene/store/TestRAMDirectory.java+++ b/lucene/core/src/test/org/apache/lucene/store/TestRAMDirectory.java@@ -175,17 +175,14 @@ public class TestRAMDirectory extends BaseDirectoryTestCase {}try (IndexInput is = dir.openInput("foo", newIOContext(random))) {- try {+ expectThrows(EOFException.class, () -> {is.seek(0);// Here, I go past EOF.is.seek(len + random().nextInt(2048));// since EOF is not enforced by the previous call in RAMInputStream// this call to readBytes should throw the exception.is.readBytes(bytes, 0, 16);- fail("Did not get EOFException");- } catch (EOFException eof) {- // expected!- }+ });}}}diff --git a/lucene/core/src/test/org/apache/lucene/store/TestSimpleFSLockFactory.java b/lucene/core/src/test/org/apache/lucene/store/TestSimpleFSLockFactory.javaindex 84bdd9f52ec..ec504980bde 100644--- a/lucene/core/src/test/org/apache/lucene/store/TestSimpleFSLockFactory.java+++ b/lucene/core/src/test/org/apache/lucene/store/TestSimpleFSLockFactory.java@@ -46,14 +46,10 @@ public class TestSimpleFSLockFactory extends BaseLockFactoryTestCase {assumeNoException("test requires the ability to delete a locked file", e);}- try {+ expectThrows(IOException.class, () -> {lock.ensureValid();- fail("no exception");- } catch (IOException expected) {- // ok- } finally {- IOUtils.closeWhileHandlingException(lock);- }+ });+ IOUtils.closeWhileHandlingException(lock);} finally {// Do this in finally clause in case the assumeNoException is false:dir.close();diff --git a/lucene/core/src/test/org/apache/lucene/store/TestSingleInstanceLockFactory.java b/lucene/core/src/test/org/apache/lucene/store/TestSingleInstanceLockFactory.javaindex be0bef25ff5..14863ffb53c 100644--- a/lucene/core/src/test/org/apache/lucene/store/TestSingleInstanceLockFactory.java+++ b/lucene/core/src/test/org/apache/lucene/store/TestSingleInstanceLockFactory.java@@ -44,16 +44,10 @@ public class TestSingleInstanceLockFactory extends BaseLockFactoryTestCase {IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(new MockAnalyzer(random())));// Create a 2nd IndexWriter. This should fail:- IndexWriter writer2 = null;- try {- writer2 = new IndexWriter(dir, new IndexWriterConfig(new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND));- fail("Should have hit an IOException with two IndexWriters on default SingleInstanceLockFactory");- } catch (IOException e) {- }+ expectThrows(IOException.class, () -> {+ new IndexWriter(dir, new IndexWriterConfig(new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND));+ });writer.close();- if (writer2 != null) {- writer2.close();- }}}diff --git a/lucene/core/src/test/org/apache/lucene/util/TestArrayUtil.java b/lucene/core/src/test/org/apache/lucene/util/TestArrayUtil.javaindex c289120bbf2..77471f943b4 100644--- a/lucene/core/src/test/org/apache/lucene/util/TestArrayUtil.java+++ b/lucene/core/src/test/org/apache/lucene/util/TestArrayUtil.java@@ -50,12 +50,9 @@ public class TestArrayUtil extends LuceneTestCase {}public void testTooBig() {- try {+ expectThrows(IllegalArgumentException.class, () -> {ArrayUtil.oversize(ArrayUtil.MAX_ARRAY_LENGTH+1, 1);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });}public void testExactLimit() {@@ -74,48 +71,32 @@ public class TestArrayUtil extends LuceneTestCase {}public void testParseInt() throws Exception {- int test;- try {- test = ArrayUtil.parseInt("".toCharArray());- assertTrue(false);- } catch (NumberFormatException e) {- //expected- }- try {- test = ArrayUtil.parseInt("foo".toCharArray());- assertTrue(false);- } catch (NumberFormatException e) {- //expected- }- try {- test = ArrayUtil.parseInt(String.valueOf(Long.MAX_VALUE).toCharArray());- assertTrue(false);- } catch (NumberFormatException e) {- //expected- }- try {- test = ArrayUtil.parseInt("0.34".toCharArray());- assertTrue(false);- } catch (NumberFormatException e) {- //expected- }+ expectThrows(NumberFormatException.class, () -> {+ ArrayUtil.parseInt("".toCharArray());+ });- try {- test = ArrayUtil.parseInt("1".toCharArray());- assertTrue(test + " does not equal: " + 1, test == 1);- test = ArrayUtil.parseInt("-10000".toCharArray());- assertTrue(test + " does not equal: " + -10000, test == -10000);- test = ArrayUtil.parseInt("1923".toCharArray());- assertTrue(test + " does not equal: " + 1923, test == 1923);- test = ArrayUtil.parseInt("-1".toCharArray());- assertTrue(test + " does not equal: " + -1, test == -1);- test = ArrayUtil.parseInt("foo 1923 bar".toCharArray(), 4, 4);- assertTrue(test + " does not equal: " + 1923, test == 1923);- } catch (NumberFormatException e) {- e.printStackTrace();- assertTrue(false);- }+ expectThrows(NumberFormatException.class, () -> {+ ArrayUtil.parseInt("foo".toCharArray());+ });++ expectThrows(NumberFormatException.class, () -> {+ ArrayUtil.parseInt(String.valueOf(Long.MAX_VALUE).toCharArray());+ });++ expectThrows(NumberFormatException.class, () -> {+ ArrayUtil.parseInt("0.34".toCharArray());+ });+ int test = ArrayUtil.parseInt("1".toCharArray());+ assertTrue(test + " does not equal: " + 1, test == 1);+ test = ArrayUtil.parseInt("-10000".toCharArray());+ assertTrue(test + " does not equal: " + -10000, test == -10000);+ test = ArrayUtil.parseInt("1923".toCharArray());+ assertTrue(test + " does not equal: " + 1923, test == 1923);+ test = ArrayUtil.parseInt("-1".toCharArray());+ assertTrue(test + " does not equal: " + -1, test == -1);+ test = ArrayUtil.parseInt("foo 1923 bar".toCharArray(), 4, 4);+ assertTrue(test + " does not equal: " + 1923, test == 1923);}public void testSliceEquals() {diff --git a/lucene/core/src/test/org/apache/lucene/util/TestAttributeSource.java b/lucene/core/src/test/org/apache/lucene/util/TestAttributeSource.javaindex 83becc740f7..df6c51392d1 100644--- a/lucene/core/src/test/org/apache/lucene/util/TestAttributeSource.java+++ b/lucene/core/src/test/org/apache/lucene/util/TestAttributeSource.java@@ -71,12 +71,10 @@ public class TestAttributeSource extends LuceneTestCase {// init a third instance missing one AttributeAttributeSource src3 = new AttributeSource();termAtt = src3.addAttribute(CharTermAttribute.class);- try {+ // The third instance is missing the TypeAttribute, so restoreState() should throw IllegalArgumentException+ expectThrows(IllegalArgumentException.class, () -> {src3.restoreState(state);- fail("The third instance is missing the TypeAttribute, so restoreState() should throw IllegalArgumentException");- } catch (IllegalArgumentException iae) {- // pass- }+ });}public void testCloneAttributes() {@@ -133,24 +131,22 @@ public class TestAttributeSource extends LuceneTestCase {@SuppressWarnings({"rawtypes","unchecked"})public void testInvalidArguments() throws Exception {- try {+ expectThrows(IllegalArgumentException.class, () -> {AttributeSource src = new AttributeSource();src.addAttribute(Token.class);fail("Should throw IllegalArgumentException");- } catch (IllegalArgumentException iae) {}+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {AttributeSource src = new AttributeSource(Token.TOKEN_ATTRIBUTE_FACTORY);src.addAttribute(Token.class);- fail("Should throw IllegalArgumentException");- } catch (IllegalArgumentException iae) {}+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {AttributeSource src = new AttributeSource();// break this by unsafe castsrc.addAttribute((Class) Iterator.class);- fail("Should throw IllegalArgumentException");- } catch (IllegalArgumentException iae) {}+ });}public void testLUCENE_3042() throws Exception {diff --git a/lucene/core/src/test/org/apache/lucene/util/TestCharsRef.java b/lucene/core/src/test/org/apache/lucene/util/TestCharsRef.javaindex c9e5a38a8a6..0a4c8844c85 100644--- a/lucene/core/src/test/org/apache/lucene/util/TestCharsRef.java+++ b/lucene/core/src/test/org/apache/lucene/util/TestCharsRef.java@@ -74,19 +74,13 @@ public class TestCharsRef extends LuceneTestCase {assertEquals('b', c.charAt(1));- try {+ expectThrows(IndexOutOfBoundsException.class, () -> {c.charAt(-1);- fail();- } catch (IndexOutOfBoundsException expected) {- // expected exception- }+ });- try {+ expectThrows(IndexOutOfBoundsException.class, () -> {c.charAt(3);- fail();- } catch (IndexOutOfBoundsException expected) {- // expected exception- }+ });}// LUCENE-3590: fix off-by-one in subsequence, and fully obey interface@@ -115,32 +109,20 @@ public class TestCharsRef extends LuceneTestCase {// empty subsequenceassertEquals("", c.subSequence(0, 0).toString());- try {+ expectThrows(IndexOutOfBoundsException.class, () -> {c.subSequence(-1, 1);- fail();- } catch (IndexOutOfBoundsException expected) {- // expected exception- }+ });- try {+ expectThrows(IndexOutOfBoundsException.class, () -> {c.subSequence(0, -1);- fail();- } catch (IndexOutOfBoundsException expected) {- // expected exception- }+ });- try {+ expectThrows(IndexOutOfBoundsException.class, () -> {c.subSequence(0, 4);- fail();- } catch (IndexOutOfBoundsException expected) {- // expected exception- }+ });- try {+ expectThrows(IndexOutOfBoundsException.class, () -> {c.subSequence(2, 1);- fail();- } catch (IndexOutOfBoundsException expected) {- // expected exception- }+ });}}diff --git a/lucene/core/src/test/org/apache/lucene/util/TestFilterIterator.java b/lucene/core/src/test/org/apache/lucene/util/TestFilterIterator.javaindex d2340cb1167..847553adfee 100644--- a/lucene/core/src/test/org/apache/lucene/util/TestFilterIterator.java+++ b/lucene/core/src/test/org/apache/lucene/util/TestFilterIterator.java@@ -28,12 +28,9 @@ public class TestFilterIterator extends LuceneTestCase {private static void assertNoMore(Iterator<?> it) {assertFalse(it.hasNext());- try {+ expectThrows(NoSuchElementException.class, () -> {it.next();- fail("Should throw NoSuchElementException");- } catch (NoSuchElementException nsee) {- // pass- }+ });assertFalse(it.hasNext());}@@ -132,12 +129,9 @@ public class TestFilterIterator extends LuceneTestCase {}};assertEquals("a", it.next());- try {+ expectThrows(UnsupportedOperationException.class, () -> {it.remove();- fail("Should throw UnsupportedOperationException");- } catch (UnsupportedOperationException oue) {- // pass- }+ });}}diff --git a/lucene/core/src/test/org/apache/lucene/util/TestIOUtils.java b/lucene/core/src/test/org/apache/lucene/util/TestIOUtils.javaindex dc9e3e75b25..f068b1184cc 100644--- a/lucene/core/src/test/org/apache/lucene/util/TestIOUtils.java+++ b/lucene/core/src/test/org/apache/lucene/util/TestIOUtils.java@@ -110,12 +110,9 @@ public class TestIOUtils extends LuceneTestCase {// exception: file doesn't existPath fake = dir.resolve("nonexistent");- try {+ expectThrows(IOException.class, () -> {IOUtils.spins(fake);- fail();- } catch (IOException expected) {- // ok- }+ });}// fake up a filestore to test some underlying methodsdiff --git a/lucene/core/src/test/org/apache/lucene/util/TestLegacyNumericUtils.java b/lucene/core/src/test/org/apache/lucene/util/TestLegacyNumericUtils.javaindex 1d9c41ed86f..621ab964342 100644--- a/lucene/core/src/test/org/apache/lucene/util/TestLegacyNumericUtils.java+++ b/lucene/core/src/test/org/apache/lucene/util/TestLegacyNumericUtils.java@@ -75,12 +75,10 @@ public class TestLegacyNumericUtils extends LuceneTestCase {assertEquals( "forward and back conversion should generate same long", vals[i], LegacyNumericUtils.prefixCodedToLong(prefixVals[i].get()) );// test if decoding values as int fails correctly- try {- LegacyNumericUtils.prefixCodedToInt(prefixVals[i].get());- fail("decoding a prefix coded long value as int should fail");- } catch (NumberFormatException e) {- // worked- }+ final int index = i;+ expectThrows(NumberFormatException.class, () -> {+ LegacyNumericUtils.prefixCodedToInt(prefixVals[index].get());+ });}// check sort order (prefixVals should be ascending)@@ -115,12 +113,10 @@ public class TestLegacyNumericUtils extends LuceneTestCase {assertEquals( "forward and back conversion should generate same int", vals[i], LegacyNumericUtils.prefixCodedToInt(prefixVals[i].get()) );// test if decoding values as long fails correctly- try {- LegacyNumericUtils.prefixCodedToLong(prefixVals[i].get());- fail("decoding a prefix coded int value as long should fail");- } catch (NumberFormatException e) {- // worked- }+ final int index = i;+ expectThrows(NumberFormatException.class, () -> {+ LegacyNumericUtils.prefixCodedToLong(prefixVals[index].get());+ });}// check sort order (prefixVals should be ascending)diff --git a/lucene/core/src/test/org/apache/lucene/util/TestNamedSPILoader.java b/lucene/core/src/test/org/apache/lucene/util/TestNamedSPILoader.javaindex 3194e7bd8de..a093090d5c4 100644--- a/lucene/core/src/test/org/apache/lucene/util/TestNamedSPILoader.java+++ b/lucene/core/src/test/org/apache/lucene/util/TestNamedSPILoader.java@@ -33,10 +33,9 @@ public class TestNamedSPILoader extends LuceneTestCase {// we want an exception if it's not found.public void testBogusLookup() {- try {+ expectThrows(IllegalArgumentException.class, () -> {Codec.forName("dskfdskfsdfksdfdsf");- fail();- } catch (IllegalArgumentException expected) {}+ });}public void testAvailableServices() {diff --git a/lucene/core/src/test/org/apache/lucene/util/TestOfflineSorter.java b/lucene/core/src/test/org/apache/lucene/util/TestOfflineSorter.javaindex 5a46c143576..53225313ade 100644--- a/lucene/core/src/test/org/apache/lucene/util/TestOfflineSorter.java+++ b/lucene/core/src/test/org/apache/lucene/util/TestOfflineSorter.java@@ -184,23 +184,17 @@ public class TestOfflineSorter extends LuceneTestCase {BufferSize.megabytes(2047);BufferSize.megabytes(1);- try {+ expectThrows(IllegalArgumentException.class, () -> {BufferSize.megabytes(2048);- fail("max mb is 2047");- } catch (IllegalArgumentException e) {- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {BufferSize.megabytes(0);- fail("min mb is 0.5");- } catch (IllegalArgumentException e) {- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {BufferSize.megabytes(-1);- fail("min mb is 0.5");- } catch (IllegalArgumentException e) {- }+ });}public void testThreadSafety() throws Exception {diff --git a/lucene/core/src/test/org/apache/lucene/util/TestPriorityQueue.java b/lucene/core/src/test/org/apache/lucene/util/TestPriorityQueue.javaindex cd202feb826..ba28490371e 100644--- a/lucene/core/src/test/org/apache/lucene/util/TestPriorityQueue.java+++ b/lucene/core/src/test/org/apache/lucene/util/TestPriorityQueue.java@@ -191,43 +191,43 @@ public class TestPriorityQueue extends LuceneTestCase {}}- public void testIterator() {+ public void testIteratorEmpty() {IntegerQueue queue = new IntegerQueue(3);Iterator<Integer> it = queue.iterator();assertFalse(it.hasNext());- try {+ expectThrows(NoSuchElementException.class, () -> {it.next();- fail();- } catch (NoSuchElementException e) {- // ok- }+ });+ }++ public void testIteratorOne() {+ IntegerQueue queue = new IntegerQueue(3);queue.add(1);- it = queue.iterator();+ Iterator<Integer> it = queue.iterator();assertTrue(it.hasNext());assertEquals(Integer.valueOf(1), it.next());assertFalse(it.hasNext());- try {+ expectThrows(NoSuchElementException.class, () -> {it.next();- fail();- } catch (NoSuchElementException e) {- // ok- }+ });+ }++ public void testIteratorTwo() {+ IntegerQueue queue = new IntegerQueue(3);+ queue.add(1);queue.add(2);- it = queue.iterator();+ Iterator<Integer> it = queue.iterator();assertTrue(it.hasNext());assertEquals(Integer.valueOf(1), it.next());assertTrue(it.hasNext());assertEquals(Integer.valueOf(2), it.next());assertFalse(it.hasNext());- try {+ expectThrows(NoSuchElementException.class, () -> {it.next();- fail();- } catch (NoSuchElementException e) {- // ok- }+ });}public void testIteratorRandom() {diff --git a/lucene/core/src/test/org/apache/lucene/util/TestUnicodeUtil.java b/lucene/core/src/test/org/apache/lucene/util/TestUnicodeUtil.javaindex 0ef25eefe7a..d86cdf2fcbb 100644--- a/lucene/core/src/test/org/apache/lucene/util/TestUnicodeUtil.java+++ b/lucene/core/src/test/org/apache/lucene/util/TestUnicodeUtil.java@@ -127,13 +127,9 @@ public class TestUnicodeUtil extends LuceneTestCase {}private void assertcodePointCountThrowsAssertionOn(byte... bytes) {- boolean threwAssertion = false;- try {+ expectThrows(IllegalArgumentException.class, () -> {UnicodeUtil.codePointCount(new BytesRef(bytes));- } catch (IllegalArgumentException e) {- threwAssertion = true;- }- assertTrue(threwAssertion);+ });}public void testUTF8toUTF32() {diff --git a/lucene/core/src/test/org/apache/lucene/util/TestVersion.java b/lucene/core/src/test/org/apache/lucene/util/TestVersion.javaindex fd02ce2b066..9feadd26383 100644--- a/lucene/core/src/test/org/apache/lucene/util/TestVersion.java+++ b/lucene/core/src/test/org/apache/lucene/util/TestVersion.java@@ -58,34 +58,25 @@ public class TestVersion extends LuceneTestCase {}public void testParseLenientlyExceptions() {- try {+ ParseException expected = expectThrows(ParseException.class, () -> {Version.parseLeniently("LUCENE");- fail();- } catch (ParseException pe) {- // pass- assertTrue(pe.getMessage().contains("LUCENE"));- }- try {+ });+ assertTrue(expected.getMessage().contains("LUCENE"));++ expected = expectThrows(ParseException.class, () -> {Version.parseLeniently("LUCENE_610");- fail();- } catch (ParseException pe) {- // pass- assertTrue(pe.getMessage().contains("LUCENE_610"));- }- try {+ });+ assertTrue(expected.getMessage().contains("LUCENE_610"));++ expected = expectThrows(ParseException.class, () -> {Version.parseLeniently("LUCENE61");- fail();- } catch (ParseException pe) {- // pass- assertTrue(pe.getMessage().contains("LUCENE61"));- }- try {+ });+ assertTrue(expected.getMessage().contains("LUCENE61"));++ expected = expectThrows(ParseException.class, () -> {Version.parseLeniently("LUCENE_6.0.0");- fail();- } catch (ParseException pe) {- // pass- assertTrue(pe.getMessage().contains("LUCENE_6.0.0"));- }+ });+ assertTrue(expected.getMessage().contains("LUCENE_6.0.0"));}public void testParseLenientlyOnAllConstants() throws Exception {@@ -116,101 +107,65 @@ public class TestVersion extends LuceneTestCase {}public void testParseExceptions() {- try {+ ParseException expected = expectThrows(ParseException.class, () -> {Version.parse("LUCENE_6_0_0");- fail();- } catch (ParseException pe) {- // pass- assertTrue(pe.getMessage().contains("LUCENE_6_0_0"));- }+ });+ assertTrue(expected.getMessage().contains("LUCENE_6_0_0"));- try {+ expected = expectThrows(ParseException.class, () -> {Version.parse("6.256");- fail();- } catch (ParseException pe) {- // pass- assertTrue(pe.getMessage().contains("6.256"));- }+ });+ assertTrue(expected.getMessage().contains("6.256"));- try {+ expected = expectThrows(ParseException.class, () -> {Version.parse("6.-1");- fail();- } catch (ParseException pe) {- // pass- assertTrue(pe.getMessage().contains("6.-1"));- }+ });+ assertTrue(expected.getMessage().contains("6.-1"));- try {+ expected = expectThrows(ParseException.class, () -> {Version.parse("6.1.256");- fail();- } catch (ParseException pe) {- // pass- assertTrue(pe.getMessage().contains("6.1.256"));- }+ });+ assertTrue(expected.getMessage().contains("6.1.256"));- try {+ expected = expectThrows(ParseException.class, () -> {Version.parse("6.1.-1");- fail();- } catch (ParseException pe) {- // pass- assertTrue(pe.getMessage().contains("6.1.-1"));- }+ });+ assertTrue(expected.getMessage().contains("6.1.-1"));- try {+ expected = expectThrows(ParseException.class, () -> {Version.parse("6.1.1.3");- fail();- } catch (ParseException pe) {- // pass- assertTrue(pe.getMessage().contains("6.1.1.3"));- }+ });+ assertTrue(expected.getMessage().contains("6.1.1.3"));- try {+ expected = expectThrows(ParseException.class, () -> {Version.parse("6.1.1.-1");- fail();- } catch (ParseException pe) {- // pass- assertTrue(pe.getMessage().contains("6.1.1.-1"));- }+ });+ assertTrue(expected.getMessage().contains("6.1.1.-1"));- try {+ expected = expectThrows(ParseException.class, () -> {Version.parse("6.1.1.1");- fail();- } catch (ParseException pe) {- // pass- assertTrue(pe.getMessage().contains("6.1.1.1"));- }+ });+ assertTrue(expected.getMessage().contains("6.1.1.1"));- try {+ expected = expectThrows(ParseException.class, () -> {Version.parse("6.1.1.2");- fail();- } catch (ParseException pe) {- // pass- assertTrue(pe.getMessage().contains("6.1.1.2"));- }+ });+ assertTrue(expected.getMessage().contains("6.1.1.2"));- try {+ expected = expectThrows(ParseException.class, () -> {Version.parse("6.0.0.0");- fail();- } catch (ParseException pe) {- // pass- assertTrue(pe.getMessage().contains("6.0.0.0"));- }+ });+ assertTrue(expected.getMessage().contains("6.0.0.0"));- try {+ expected = expectThrows(ParseException.class, () -> {Version.parse("6.0.0.1.42");- fail();- } catch (ParseException pe) {- // pass- assertTrue(pe.getMessage().contains("6.0.0.1.42"));- }+ });+ assertTrue(expected.getMessage().contains("6.0.0.1.42"));- try {+ expected = expectThrows(ParseException.class, () -> {Version.parse("6..0.1");- fail();- } catch (ParseException pe) {- // pass- assertTrue(pe.getMessage().contains("6..0.1"));- }+ });+ assertTrue(expected.getMessage().contains("6..0.1"));}public void testDeprecations() throws Exception {diff --git a/lucene/core/src/test/org/apache/lucene/util/TestVirtualMethod.java b/lucene/core/src/test/org/apache/lucene/util/TestVirtualMethod.javaindex 38d217dd77f..4dfe86b3f50 100644--- a/lucene/core/src/test/org/apache/lucene/util/TestVirtualMethod.java+++ b/lucene/core/src/test/org/apache/lucene/util/TestVirtualMethod.java@@ -16,7 +16,6 @@*/package org.apache.lucene.util;-public class TestVirtualMethod extends LuceneTestCase {private static final VirtualMethod<TestVirtualMethod> publicTestMethod =@@ -71,35 +70,26 @@ public class TestVirtualMethod extends LuceneTestCase {@SuppressWarnings({"rawtypes","unchecked"})public void testExceptions() {- try {+ // LuceneTestCase is not a subclass and can never override publicTest(String)+ expectThrows(IllegalArgumentException.class, () -> {// cast to Class to remove generics:publicTestMethod.getImplementationDistance((Class) LuceneTestCase.class);- fail("LuceneTestCase is not a subclass and can never override publicTest(String)");- } catch (IllegalArgumentException arg) {- // pass- }+ });- try {+ // Method bogus() does not exist, so IAE should be thrown+ expectThrows(IllegalArgumentException.class, () -> {new VirtualMethod<>(TestVirtualMethod.class, "bogus");- fail("Method bogus() does not exist, so IAE should be thrown");- } catch (IllegalArgumentException arg) {- // pass- }+ });- try {+ // Method publicTest(String) is not declared in TestClass2, so IAE should be thrown+ expectThrows(IllegalArgumentException.class, () -> {new VirtualMethod<>(TestClass2.class, "publicTest", String.class);- fail("Method publicTest(String) is not declared in TestClass2, so IAE should be thrown");- } catch (IllegalArgumentException arg) {- // pass- }+ });- try {- // try to create a second instance of the same baseClass / method combination+ // try to create a second instance of the same baseClass / method combination+ expectThrows(UnsupportedOperationException.class, () -> {new VirtualMethod<>(TestVirtualMethod.class, "publicTest", String.class);- fail("Violating singleton status succeeded");- } catch (UnsupportedOperationException arg) {- // pass- }+ });}}diff --git a/lucene/core/src/test/org/apache/lucene/util/TestWeakIdentityMap.java b/lucene/core/src/test/org/apache/lucene/util/TestWeakIdentityMap.javaindex 4e0c7a5cf2f..76e42ab8722 100644--- a/lucene/core/src/test/org/apache/lucene/util/TestWeakIdentityMap.java+++ b/lucene/core/src/test/org/apache/lucene/util/TestWeakIdentityMap.java@@ -141,11 +141,9 @@ public class TestWeakIdentityMap extends LuceneTestCase {Iterator<String> it = map.keyIterator();assertFalse(it.hasNext());- try {+ expectThrows(NoSuchElementException.class, () -> {it.next();- fail("Should throw NoSuchElementException");- } catch (NoSuchElementException nse) {- }+ });key1 = new String("foo");key2 = new String("foo");diff --git a/lucene/core/src/test/org/apache/lucene/util/automaton/FiniteStringsIteratorTest.java b/lucene/core/src/test/org/apache/lucene/util/automaton/FiniteStringsIteratorTest.javaindex 57113d086e4..4edc7ad1a40 100644--- a/lucene/core/src/test/org/apache/lucene/util/automaton/FiniteStringsIteratorTest.java+++ b/lucene/core/src/test/org/apache/lucene/util/automaton/FiniteStringsIteratorTest.java@@ -17,6 +17,7 @@package org.apache.lucene.util.automaton;+import org.apache.lucene.store.AlreadyClosedException;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.IntsRef;import org.apache.lucene.util.IntsRefBuilder;@@ -133,14 +134,11 @@ public class FiniteStringsIteratorTest extends LuceneTestCase {public void testWithCycle() throws Exception {- try {+ expectThrows(IllegalArgumentException.class, () -> {Automaton a = new RegExp("abc.*", RegExp.NONE).toAutomaton();FiniteStringsIterator iterator = new FiniteStringsIterator(a);getFiniteStrings(iterator);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });}public void testSingletonNoLimit() {diff --git a/lucene/core/src/test/org/apache/lucene/util/automaton/LimitedFiniteStringsIteratorTest.java b/lucene/core/src/test/org/apache/lucene/util/automaton/LimitedFiniteStringsIteratorTest.javaindex ddaa65a2827..53034175111 100644--- a/lucene/core/src/test/org/apache/lucene/util/automaton/LimitedFiniteStringsIteratorTest.java+++ b/lucene/core/src/test/org/apache/lucene/util/automaton/LimitedFiniteStringsIteratorTest.java@@ -19,6 +19,7 @@ package org.apache.lucene.util.automaton;import java.util.List;+import org.apache.lucene.store.AlreadyClosedException;import org.apache.lucene.util.IntsRef;import org.apache.lucene.util.IntsRefBuilder;import org.apache.lucene.util.LuceneTestCase;@@ -52,22 +53,17 @@ public class LimitedFiniteStringsIteratorTest extends LuceneTestCase {public void testInvalidLimitNegative() {Automaton a = AutomatonTestUtil.randomAutomaton(random());- try {+ expectThrows(IllegalArgumentException.class, () -> {new LimitedFiniteStringsIterator(a, -7);fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });}public void testInvalidLimitNull() {Automaton a = AutomatonTestUtil.randomAutomaton(random());- try {+ expectThrows(IllegalArgumentException.class, () -> {new LimitedFiniteStringsIterator(a, 0);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });}public void testSingleton() {diff --git a/lucene/core/src/test/org/apache/lucene/util/automaton/TestAutomaton.java b/lucene/core/src/test/org/apache/lucene/util/automaton/TestAutomaton.javaindex 83c573800fe..e4a09dceff2 100644--- a/lucene/core/src/test/org/apache/lucene/util/automaton/TestAutomaton.java+++ b/lucene/core/src/test/org/apache/lucene/util/automaton/TestAutomaton.java@@ -325,12 +325,9 @@ public class TestAutomaton extends LuceneTestCase {int s2 = a.createState();a.addTransition(s1, s2, 'a');a.addTransition(s2, s2, 'a');- try {+ expectThrows(IllegalStateException.class, () -> {a.addTransition(s1, s2, 'b');- fail("didn't hit expected exception");- } catch (IllegalStateException ise) {- // expected- }+ });}public void testBuilderRandom() throws Exception {diff --git a/lucene/core/src/test/org/apache/lucene/util/automaton/TestRegExp.java b/lucene/core/src/test/org/apache/lucene/util/automaton/TestRegExp.javaindex afb8e36001e..b9ac6192c82 100644--- a/lucene/core/src/test/org/apache/lucene/util/automaton/TestRegExp.java+++ b/lucene/core/src/test/org/apache/lucene/util/automaton/TestRegExp.java@@ -48,34 +48,30 @@ public class TestRegExp extends LuceneTestCase {public void testDeterminizeTooManyStates() {// LUCENE-6046String source = "[ac]*a[ac]{50,200}";- try {+ TooComplexToDeterminizeException expected = expectThrows(TooComplexToDeterminizeException.class, () -> {new RegExp(source).toAutomaton();- fail();- } catch (TooComplexToDeterminizeException e) {- assert(e.getMessage().contains(source));- }+ });+ assertTrue(expected.getMessage().contains(source));}// LUCENE-6713public void testSerializeTooManyStatesToDeterminizeExc() throws Exception {// LUCENE-6046String source = "[ac]*a[ac]{50,200}";- try {+ TooComplexToDeterminizeException expected = expectThrows(TooComplexToDeterminizeException.class, () -> {new RegExp(source).toAutomaton();- fail();- } catch (TooComplexToDeterminizeException e) {- assert(e.getMessage().contains(source));+ });+ assertTrue(expected.getMessage().contains(source));- ByteArrayOutputStream bos = new ByteArrayOutputStream();- ObjectOutput out = new ObjectOutputStream(bos);- out.writeObject(e);- byte[] bytes = bos.toByteArray();+ ByteArrayOutputStream bos = new ByteArrayOutputStream();+ ObjectOutput out = new ObjectOutputStream(bos);+ out.writeObject(expected);+ byte[] bytes = bos.toByteArray();- ByteArrayInputStream bis = new ByteArrayInputStream(bytes);- ObjectInput in = new ObjectInputStream(bis);- TooComplexToDeterminizeException e2 = (TooComplexToDeterminizeException) in.readObject();- assertNotNull(e2.getMessage());- }+ ByteArrayInputStream bis = new ByteArrayInputStream(bytes);+ ObjectInput in = new ObjectInputStream(bis);+ TooComplexToDeterminizeException e2 = (TooComplexToDeterminizeException) in.readObject();+ assertNotNull(e2.getMessage());}// LUCENE-6046diff --git a/lucene/core/src/test/org/apache/lucene/util/bkd/TestBKD.java b/lucene/core/src/test/org/apache/lucene/util/bkd/TestBKD.javaindex 67819bdd48f..8cee5c6608c 100644--- a/lucene/core/src/test/org/apache/lucene/util/bkd/TestBKD.java+++ b/lucene/core/src/test/org/apache/lucene/util/bkd/TestBKD.java@@ -429,11 +429,10 @@ public class TestBKD extends LuceneTestCase {public void testTooLittleHeap() throws Exception {try (Directory dir = getDirectory(0)) {- new BKDWriter(dir, "bkd", 1, 16, 1000000, 0.001);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- assertTrue(iae.getMessage().contains("either increase maxMBSortInHeap or decrease maxPointsInLeafNode"));+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ new BKDWriter(dir, "bkd", 1, 16, 1000000, 0.001);+ });+ assertTrue(expected.getMessage().contains("either increase maxMBSortInHeap or decrease maxPointsInLeafNode"));}}@@ -563,11 +562,10 @@ public class TestBKD extends LuceneTestCase {Arrays.fill(bytes, (byte) 0xff);byte[] one = new byte[4];one[3] = 1;- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {NumericUtils.add(4, 0, bytes, one, new byte[4]);- } catch (IllegalArgumentException iae) {- assertEquals("a + b overflows bytesPerDim=4", iae.getMessage());- }+ });+ assertEquals("a + b overflows bytesPerDim=4", expected.getMessage());}public void testNumericUtilsSubtract() throws Exception {@@ -607,11 +605,10 @@ public class TestBKD extends LuceneTestCase {v1[3] = (byte) 0xf0;byte[] v2 = new byte[4];v2[3] = (byte) 0xf1;- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {NumericUtils.subtract(4, 0, v1, v2, new byte[4]);- } catch (IllegalArgumentException iae) {- assertEquals("a < b", iae.getMessage());- }+ });+ assertEquals("a < b", expected.getMessage());}/** docIDs can be null, for the single valued case, else it maps value to docID */diff --git a/lucene/core/src/test/org/apache/lucene/util/packed/TestDirectPacked.java b/lucene/core/src/test/org/apache/lucene/util/packed/TestDirectPacked.javaindex 4d72a69c283..774a2ce44e9 100644--- a/lucene/core/src/test/org/apache/lucene/util/packed/TestDirectPacked.java+++ b/lucene/core/src/test/org/apache/lucene/util/packed/TestDirectPacked.java@@ -66,12 +66,11 @@ public class TestDirectPacked extends LuceneTestCase {writer.add(0);writer.add(2);writer.add(1);- try {+ IllegalStateException expected = expectThrows(IllegalStateException.class, () -> {writer.finish();- fail("didn't get expected exception");- } catch (IllegalStateException expected) {- assertTrue(expected.getMessage().startsWith("Wrong number of values added"));- }+ });+ assertTrue(expected.getMessage().startsWith("Wrong number of values added"));+output.close();dir.close();}diff --git a/lucene/core/src/test/org/apache/lucene/util/packed/TestPackedInts.java b/lucene/core/src/test/org/apache/lucene/util/packed/TestPackedInts.javaindex 40621346eed..ce3447eef2f 100644--- a/lucene/core/src/test/org/apache/lucene/util/packed/TestPackedInts.java+++ b/lucene/core/src/test/org/apache/lucene/util/packed/TestPackedInts.java@@ -1033,12 +1033,9 @@ public class TestPackedInts extends LuceneTestCase {}assertEquals(arr.length, buf.size());final PackedLongValues values = buf.build();- try {+ expectThrows(IllegalStateException.class, () -> {buf.add(random().nextLong());- fail("expected an exception");- } catch (IllegalStateException e) {- // ok- }+ });assertEquals(arr.length, values.size());for (int i = 0; i < arr.length; ++i) {@@ -1160,12 +1157,9 @@ public class TestPackedInts extends LuceneTestCase {assertEquals(i, it.ord());}assertEquals(fp, in instanceof ByteArrayDataInput ? ((ByteArrayDataInput) in).getPosition() : ((IndexInput) in).getFilePointer());- try {+ expectThrows(IOException.class, () -> {it.next();- assertTrue(false);- } catch (IOException e) {- // OK- }+ });if (in instanceof ByteArrayDataInput) {((ByteArrayDataInput) in).setPosition(0);@@ -1187,12 +1181,9 @@ public class TestPackedInts extends LuceneTestCase {}}assertEquals(fp, in instanceof ByteArrayDataInput ? ((ByteArrayDataInput) in).getPosition() : ((IndexInput) in).getFilePointer());- try {+ expectThrows(IOException.class, () -> {it2.skip(1);- assertTrue(false);- } catch (IOException e) {- // OK- }+ });in1.seek(0L);final BlockPackedReader reader = new BlockPackedReader(in1, PackedInts.VERSION_CURRENT, blockSize, valueCount, random().nextBoolean());diff --git a/lucene/expressions/src/test/org/apache/lucene/expressions/TestExpressionValidation.java b/lucene/expressions/src/test/org/apache/lucene/expressions/TestExpressionValidation.javaindex 9aa9a39f346..56086b90a44 100644--- a/lucene/expressions/src/test/org/apache/lucene/expressions/TestExpressionValidation.java+++ b/lucene/expressions/src/test/org/apache/lucene/expressions/TestExpressionValidation.java@@ -42,47 +42,39 @@ public class TestExpressionValidation extends LuceneTestCase {SimpleBindings bindings = new SimpleBindings();bindings.add(new SortField("valid", SortField.Type.INT));bindings.add("invalid", JavascriptCompiler.compile("badreference"));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {bindings.validate();- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Invalid reference"));- }+ });+ assertTrue(expected.getMessage().contains("Invalid reference"));}public void testInvalidExternal2() throws Exception {SimpleBindings bindings = new SimpleBindings();bindings.add(new SortField("valid", SortField.Type.INT));bindings.add("invalid", JavascriptCompiler.compile("valid + badreference"));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {bindings.validate();- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Invalid reference"));- }+ });+ assertTrue(expected.getMessage().contains("Invalid reference"));}public void testSelfRecursion() throws Exception {SimpleBindings bindings = new SimpleBindings();bindings.add("cycle0", JavascriptCompiler.compile("cycle0"));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {bindings.validate();- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Cycle detected"));- }+ });+ assertTrue(expected.getMessage().contains("Cycle detected"));}public void testCoRecursion() throws Exception {SimpleBindings bindings = new SimpleBindings();bindings.add("cycle0", JavascriptCompiler.compile("cycle1"));bindings.add("cycle1", JavascriptCompiler.compile("cycle0"));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {bindings.validate();- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Cycle detected"));- }+ });+ assertTrue(expected.getMessage().contains("Cycle detected"));}public void testCoRecursion2() throws Exception {@@ -90,12 +82,10 @@ public class TestExpressionValidation extends LuceneTestCase {bindings.add("cycle0", JavascriptCompiler.compile("cycle1"));bindings.add("cycle1", JavascriptCompiler.compile("cycle2"));bindings.add("cycle2", JavascriptCompiler.compile("cycle0"));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {bindings.validate();- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Cycle detected"));- }+ });+ assertTrue(expected.getMessage().contains("Cycle detected"));}public void testCoRecursion3() throws Exception {@@ -103,12 +93,10 @@ public class TestExpressionValidation extends LuceneTestCase {bindings.add("cycle0", JavascriptCompiler.compile("100"));bindings.add("cycle1", JavascriptCompiler.compile("cycle0 + cycle2"));bindings.add("cycle2", JavascriptCompiler.compile("cycle0 + cycle1"));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {bindings.validate();- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Cycle detected"));- }+ });+ assertTrue(expected.getMessage().contains("Cycle detected"));}public void testCoRecursion4() throws Exception {@@ -117,11 +105,9 @@ public class TestExpressionValidation extends LuceneTestCase {bindings.add("cycle1", JavascriptCompiler.compile("100"));bindings.add("cycle2", JavascriptCompiler.compile("cycle1 + cycle0 + cycle3"));bindings.add("cycle3", JavascriptCompiler.compile("cycle0 + cycle1 + cycle2"));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {bindings.validate();- fail("didn't get expected exception");- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Cycle detected"));- }+ });+ assertTrue(expected.getMessage().contains("Cycle detected"));}}diff --git a/lucene/expressions/src/test/org/apache/lucene/expressions/js/TestCustomFunctions.java b/lucene/expressions/src/test/org/apache/lucene/expressions/js/TestCustomFunctions.javaindex ca807e28b9a..7c46b05e2c0 100644--- a/lucene/expressions/src/test/org/apache/lucene/expressions/js/TestCustomFunctions.java+++ b/lucene/expressions/src/test/org/apache/lucene/expressions/js/TestCustomFunctions.java@@ -39,13 +39,11 @@ public class TestCustomFunctions extends LuceneTestCase {/** empty list of methods */public void testEmpty() throws Exception {Map<String,Method> functions = Collections.emptyMap();- try {+ ParseException expected = expectThrows(ParseException.class, () -> {JavascriptCompiler.compile("sqrt(20)", functions, getClass().getClassLoader());- fail();- } catch (ParseException expected) {- assertEquals("Invalid expression 'sqrt(20)': Unrecognized function call (sqrt).", expected.getMessage());- assertEquals(expected.getErrorOffset(), 0);- }+ });+ assertEquals("Invalid expression 'sqrt(20)': Unrecognized function call (sqrt).", expected.getMessage());+ assertEquals(expected.getErrorOffset(), 0);}/** using the default map explicitly */@@ -96,38 +94,23 @@ public class TestCustomFunctions extends LuceneTestCase {/** tests invalid methods that are not allowed to become variables to be mapped */public void testInvalidVariableMethods() {- try {+ ParseException expected = expectThrows(ParseException.class, () -> {JavascriptCompiler.compile("method()");- fail();- } catch (IllegalArgumentException exception) {- fail();- } catch (ParseException expected) {- //expected- assertEquals("Invalid expression 'method()': Unrecognized function call (method).", expected.getMessage());- assertEquals(0, expected.getErrorOffset());- }+ });+ assertEquals("Invalid expression 'method()': Unrecognized function call (method).", expected.getMessage());+ assertEquals(0, expected.getErrorOffset());- try {+ expected = expectThrows(ParseException.class, () -> {JavascriptCompiler.compile("method.method(1)");- fail();- } catch (IllegalArgumentException exception) {- fail();- } catch (ParseException expected) {- //expected- assertEquals("Invalid expression 'method.method(1)': Unrecognized function call (method.method).", expected.getMessage());- assertEquals(0, expected.getErrorOffset());- }+ });+ assertEquals("Invalid expression 'method.method(1)': Unrecognized function call (method.method).", expected.getMessage());+ assertEquals(0, expected.getErrorOffset());- try {+ expected = expectThrows(ParseException.class, () -> {JavascriptCompiler.compile("1 + method()");- fail();- } catch (IllegalArgumentException exception) {- fail();- } catch (ParseException expected) {- //expected- assertEquals("Invalid expression '1 + method()': Unrecognized function call (method).", expected.getMessage());- assertEquals(4, expected.getErrorOffset());- }+ });+ assertEquals("Invalid expression '1 + method()': Unrecognized function call (method).", expected.getMessage());+ assertEquals(4, expected.getErrorOffset());}public static String bogusReturnType() { return "bogus!"; }@@ -136,12 +119,10 @@ public class TestCustomFunctions extends LuceneTestCase {public void testWrongReturnType() throws Exception {Map<String,Method> functions = new HashMap<>();functions.put("foo", getClass().getMethod("bogusReturnType"));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {JavascriptCompiler.compile("foo()", functions, getClass().getClassLoader());- fail();- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("does not return a double"));- }+ });+ assertTrue(expected.getMessage().contains("does not return a double"));}public static double bogusParameterType(String s) { return 0; }@@ -150,12 +131,10 @@ public class TestCustomFunctions extends LuceneTestCase {public void testWrongParameterType() throws Exception {Map<String,Method> functions = new HashMap<>();functions.put("foo", getClass().getMethod("bogusParameterType", String.class));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {JavascriptCompiler.compile("foo(2)", functions, getClass().getClassLoader());- fail();- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("must take only double parameters"));- }+ });+ assertTrue(expected.getMessage().contains("must take only double parameters"));}public double nonStaticMethod() { return 0; }@@ -164,12 +143,10 @@ public class TestCustomFunctions extends LuceneTestCase {public void testWrongNotStatic() throws Exception {Map<String,Method> functions = new HashMap<>();functions.put("foo", getClass().getMethod("nonStaticMethod"));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {JavascriptCompiler.compile("foo()", functions, getClass().getClassLoader());- fail();- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("is not static"));- }+ });+ assertTrue(expected.getMessage().contains("is not static"));}static double nonPublicMethod() { return 0; }@@ -178,12 +155,10 @@ public class TestCustomFunctions extends LuceneTestCase {public void testWrongNotPublic() throws Exception {Map<String,Method> functions = new HashMap<>();functions.put("foo", getClass().getDeclaredMethod("nonPublicMethod"));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {JavascriptCompiler.compile("foo()", functions, getClass().getClassLoader());- fail();- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("not public"));- }+ });+ assertTrue(expected.getMessage().contains("not public"));}static class NestedNotPublic {@@ -194,12 +169,10 @@ public class TestCustomFunctions extends LuceneTestCase {public void testWrongNestedNotPublic() throws Exception {Map<String,Method> functions = new HashMap<>();functions.put("foo", NestedNotPublic.class.getMethod("method"));- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {JavascriptCompiler.compile("foo()", functions, getClass().getClassLoader());- fail();- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("not public"));- }+ });+ assertTrue(expected.getMessage().contains("not public"));}/** Classloader that can be used to create a fake static class that has one method returning a static var */@@ -250,12 +223,10 @@ public class TestCustomFunctions extends LuceneTestCase {assertEquals(2.0, expr.evaluate(0, null), DELTA);// use our classloader, not the foreign one, which should fail!- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {JavascriptCompiler.compile("bar()", functions, thisLoader);- fail();- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("is not declared by a class which is accessible by the given parent ClassLoader"));- }+ });+ assertTrue(expected.getMessage().contains("is not declared by a class which is accessible by the given parent ClassLoader"));// mix foreign and default functionsMap<String,Method> mixedFunctions = new HashMap<>(JavascriptCompiler.DEFAULT_FUNCTIONS);@@ -266,12 +237,10 @@ public class TestCustomFunctions extends LuceneTestCase {assertEquals(Math.sqrt(20), expr.evaluate(0, null), DELTA);// use our classloader, not the foreign one, which should fail!- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {JavascriptCompiler.compile("bar()", mixedFunctions, thisLoader);- fail();- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("is not declared by a class which is accessible by the given parent ClassLoader"));- }+ });+ assertTrue(expected.getMessage().contains("is not declared by a class which is accessible by the given parent ClassLoader"));}static String MESSAGE = "This should not happen but it happens";@@ -286,17 +255,15 @@ public class TestCustomFunctions extends LuceneTestCase {functions.put("foo", StaticThrowingException.class.getMethod("method"));String source = "3 * foo() / 5";Expression expr = JavascriptCompiler.compile(source, functions, getClass().getClassLoader());- try {+ ArithmeticException expected = expectThrows(ArithmeticException.class, () -> {expr.evaluate(0, null);- fail();- } catch (ArithmeticException e) {- assertEquals(MESSAGE, e.getMessage());- StringWriter sw = new StringWriter();- PrintWriter pw = new PrintWriter(sw);- e.printStackTrace(pw);- pw.flush();- assertTrue(sw.toString().contains("JavascriptCompiler$CompiledExpression.evaluate(" + source + ")"));- }+ });+ assertEquals(MESSAGE, expected.getMessage());+ StringWriter sw = new StringWriter();+ PrintWriter pw = new PrintWriter(sw);+ expected.printStackTrace(pw);+ pw.flush();+ assertTrue(sw.toString().contains("JavascriptCompiler$CompiledExpression.evaluate(" + source + ")"));}/** test that namespaces work with custom expressions. */diff --git a/lucene/expressions/src/test/org/apache/lucene/expressions/js/TestJavascriptCompiler.java b/lucene/expressions/src/test/org/apache/lucene/expressions/js/TestJavascriptCompiler.javaindex 8a9532173eb..99418651e3a 100644--- a/lucene/expressions/src/test/org/apache/lucene/expressions/js/TestJavascriptCompiler.java+++ b/lucene/expressions/src/test/org/apache/lucene/expressions/js/TestJavascriptCompiler.java@@ -90,124 +90,84 @@ public class TestJavascriptCompiler extends LuceneTestCase {}void doTestInvalidVariable(String variable) {- try {+ expectThrows(ParseException.class, () -> {JavascriptCompiler.compile(variable);- fail("\"" + variable + " should have failed to compile");- }- catch (ParseException expected) {- //expected- }+ });}public void testInvalidLexer() throws Exception {- try {+ ParseException expected = expectThrows(ParseException.class, () -> {JavascriptCompiler.compile("\n .");- fail();- } catch (ParseException pe) {- assertTrue(pe.getMessage().contains("unexpected character '.' on line (2) position (1)"));- }+ });+ assertTrue(expected.getMessage().contains("unexpected character '.' on line (2) position (1)"));}public void testInvalidCompiles() throws Exception {- try {+ expectThrows(ParseException.class, () -> {JavascriptCompiler.compile("100 100");- fail();- } catch (ParseException expected) {- // expected exception- }+ });- try {+ expectThrows(ParseException.class, () -> {JavascriptCompiler.compile("7*/-8");- fail();- } catch (ParseException expected) {- // expected exception- }+ });- try {+ expectThrows(ParseException.class, () -> {JavascriptCompiler.compile("0y1234");- fail();- } catch (ParseException expected) {- // expected exception- }+ });- try {+ expectThrows(ParseException.class, () -> {JavascriptCompiler.compile("500EE");- fail();- } catch (ParseException expected) {- // expected exception- }+ });- try {+ expectThrows(ParseException.class, () -> {JavascriptCompiler.compile("500.5EE");- fail();- } catch (ParseException expected) {- // expected exception- }+ });}public void testEmpty() {- try {+ expectThrows(ParseException.class, () -> {JavascriptCompiler.compile("");- fail();- } catch (ParseException expected) {- // expected exception- }+ });- try {+ expectThrows(ParseException.class, () -> {JavascriptCompiler.compile("()");- fail();- } catch (ParseException expected) {- // expected exception- }+ });- try {+ expectThrows(ParseException.class, () -> {JavascriptCompiler.compile(" \r\n \n \t");- fail();- } catch (ParseException expected) {- // expected exception- }+ });}public void testNull() throws Exception {- try {+ expectThrows(NullPointerException.class, () -> {JavascriptCompiler.compile(null);- fail();- } catch (NullPointerException expected) {- // expected exception- }+ });}public void testWrongArity() throws Exception {- try {+ ParseException expected = expectThrows(ParseException.class, () -> {JavascriptCompiler.compile("tan()");fail();- } catch (ParseException expected) {- assertEquals("Invalid expression 'tan()': Expected (1) arguments for function call (tan), but found (0).", expected.getMessage());- assertEquals(expected.getErrorOffset(), 0);- }+ });+ assertEquals("Invalid expression 'tan()': Expected (1) arguments for function call (tan), but found (0).", expected.getMessage());+ assertEquals(expected.getErrorOffset(), 0);- try {+ expected = expectThrows(ParseException.class, () -> {JavascriptCompiler.compile("tan(1, 1)");- fail();- } catch (ParseException expected) {- assertTrue(expected.getMessage().contains("arguments for function call"));- }+ });+ assertTrue(expected.getMessage().contains("arguments for function call"));- try {+ expected = expectThrows(ParseException.class, () -> {JavascriptCompiler.compile(" tan()");- fail();- } catch (ParseException expected) {- assertEquals("Invalid expression ' tan()': Expected (1) arguments for function call (tan), but found (0).", expected.getMessage());- assertEquals(expected.getErrorOffset(), 1);- }+ });+ assertEquals("Invalid expression ' tan()': Expected (1) arguments for function call (tan), but found (0).", expected.getMessage());+ assertEquals(expected.getErrorOffset(), 1);- try {+ expected = expectThrows(ParseException.class, () -> {JavascriptCompiler.compile("1 + tan()");- fail();- } catch (ParseException expected) {- assertEquals("Invalid expression '1 + tan()': Expected (1) arguments for function call (tan), but found (0).", expected.getMessage());- assertEquals(expected.getErrorOffset(), 4);- }+ });+ assertEquals("Invalid expression '1 + tan()': Expected (1) arguments for function call (tan), but found (0).", expected.getMessage());+ assertEquals(expected.getErrorOffset(), 4);}public void testVariableNormalization() throws Exception {diff --git a/lucene/facet/src/test/org/apache/lucene/facet/range/TestRangeFacetCounts.java b/lucene/facet/src/test/org/apache/lucene/facet/range/TestRangeFacetCounts.javaindex 27e1bd6fa47..7d154b326e0 100644--- a/lucene/facet/src/test/org/apache/lucene/facet/range/TestRangeFacetCounts.java+++ b/lucene/facet/src/test/org/apache/lucene/facet/range/TestRangeFacetCounts.java@@ -104,32 +104,19 @@ public class TestRangeFacetCounts extends FacetTestCase {d.close();}- @SuppressWarnings("unused")public void testUselessRange() {- try {+ expectThrows(IllegalArgumentException.class, () -> {new LongRange("useless", 7, true, 6, true);- fail("did not hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {new LongRange("useless", 7, true, 7, false);- fail("did not hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {new DoubleRange("useless", 7.0, true, 6.0, true);- fail("did not hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {new DoubleRange("useless", 7.0, true, 7.0, false);- fail("did not hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });}public void testLongMinMax() throws Exception {diff --git a/lucene/facet/src/test/org/apache/lucene/facet/sortedset/TestSortedSetDocValuesFacets.java b/lucene/facet/src/test/org/apache/lucene/facet/sortedset/TestSortedSetDocValuesFacets.javaindex 736a8a7d664..7659be80ec8 100644--- a/lucene/facet/src/test/org/apache/lucene/facet/sortedset/TestSortedSetDocValuesFacets.java+++ b/lucene/facet/src/test/org/apache/lucene/facet/sortedset/TestSortedSetDocValuesFacets.java@@ -124,12 +124,9 @@ public class TestSortedSetDocValuesFacets extends FacetTestCase {searcher.search(new MatchAllDocsQuery(), c);- try {+ expectThrows(IllegalStateException.class, () -> {new SortedSetDocValuesFacetCounts(state, c);- fail("did not hit expected exception");- } catch (IllegalStateException ise) {- // expected- }+ });r.close();writer.close();diff --git a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestFacetLabel.java b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestFacetLabel.javaindex 41171b3c705..436c78bb225 100644--- a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestFacetLabel.java+++ b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestFacetLabel.java@@ -155,110 +155,61 @@ public class TestFacetLabel extends FacetTestCase {new String[] { "test", null, "foo" }, // null in the middle};+ // empty or null components should not be allowed.for (String[] components : components_tests) {- try {- assertNotNull(new FacetLabel(components));- fail("empty or null components should not be allowed: " + Arrays.toString(components));- } catch (IllegalArgumentException e) {- // expected- }- try {+ expectThrows(IllegalArgumentException.class, () -> {+ new FacetLabel(components);+ });+ expectThrows(IllegalArgumentException.class, () -> {new FacetField("dim", components);- fail("empty or null components should not be allowed: " + Arrays.toString(components));- } catch (IllegalArgumentException e) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {new AssociationFacetField(new BytesRef(), "dim", components);- fail("empty or null components should not be allowed: " + Arrays.toString(components));- } catch (IllegalArgumentException e) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {new IntAssociationFacetField(17, "dim", components);- fail("empty or null components should not be allowed: " + Arrays.toString(components));- } catch (IllegalArgumentException e) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {new FloatAssociationFacetField(17.0f, "dim", components);- fail("empty or null components should not be allowed: " + Arrays.toString(components));- } catch (IllegalArgumentException e) {- // expected- }+ });}- try {++ expectThrows(IllegalArgumentException.class, () -> {new FacetField(null, new String[] {"abc"});- fail("empty or null components should not be allowed");- } catch (IllegalArgumentException e) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {new FacetField("", new String[] {"abc"});- fail("empty or null components should not be allowed");- } catch (IllegalArgumentException e) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {new IntAssociationFacetField(17, null, new String[] {"abc"});- fail("empty or null components should not be allowed");- } catch (IllegalArgumentException e) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {new IntAssociationFacetField(17, "", new String[] {"abc"});- fail("empty or null components should not be allowed");- } catch (IllegalArgumentException e) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {new FloatAssociationFacetField(17.0f, null, new String[] {"abc"});- fail("empty or null components should not be allowed");- } catch (IllegalArgumentException e) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {new FloatAssociationFacetField(17.0f, "", new String[] {"abc"});- fail("empty or null components should not be allowed");- } catch (IllegalArgumentException e) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {new AssociationFacetField(new BytesRef(), null, new String[] {"abc"});- fail("empty or null components should not be allowed");- } catch (IllegalArgumentException e) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {new AssociationFacetField(new BytesRef(), "", new String[] {"abc"});- fail("empty or null components should not be allowed");- } catch (IllegalArgumentException e) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {new SortedSetDocValuesFacetField(null, "abc");- fail("empty or null components should not be allowed");- } catch (IllegalArgumentException e) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {new SortedSetDocValuesFacetField("", "abc");- fail("empty or null components should not be allowed");- } catch (IllegalArgumentException e) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {new SortedSetDocValuesFacetField("dim", null);- fail("empty or null components should not be allowed");- } catch (IllegalArgumentException e) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {new SortedSetDocValuesFacetField("dim", "");- fail("empty or null components should not be allowed");- } catch (IllegalArgumentException e) {- // expected- }+ });}@Test@@ -273,11 +224,10 @@ public class TestFacetLabel extends FacetTestCase {break;}- try {- assertNotNull(new FacetLabel("dim", bigComp));- fail("long paths should not be allowed; len=" + bigComp.length());- } catch (IllegalArgumentException e) {- // expected- }+ // long paths should not be allowed+ final String longPath = bigComp;+ expectThrows(IllegalArgumentException.class, () -> {+ new FacetLabel("dim", longPath);+ });}}diff --git a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestSearcherTaxonomyManager.java b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestSearcherTaxonomyManager.javaindex c6a8b5fccae..a1e034406cc 100644--- a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestSearcherTaxonomyManager.java+++ b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestSearcherTaxonomyManager.java@@ -274,12 +274,9 @@ public class TestSearcherTaxonomyManager extends FacetTestCase {tw.replaceTaxonomy(taxoDir2);taxoDir2.close();- try {+ expectThrows(IllegalStateException.class, () -> {mgr.maybeRefresh();- fail("should have hit exception");- } catch (IllegalStateException ise) {- // expected- }+ });w.close();IOUtils.close(mgr, tw, taxoDir, dir);diff --git a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyCombined.java b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyCombined.javaindex 559683f6cf5..ecf14014b2f 100644--- a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyCombined.java+++ b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyCombined.java@@ -490,25 +490,15 @@ public class TestTaxonomyCombined extends FacetTestCase {}// check parent of of invalid ordinals:- try {+ expectThrows(ArrayIndexOutOfBoundsException.class, () -> {tw.getParent(-1);- fail("getParent for -1 should throw exception");- } catch (ArrayIndexOutOfBoundsException e) {- // ok- }- try {+ });+ expectThrows(ArrayIndexOutOfBoundsException.class, () -> {tw.getParent(TaxonomyReader.INVALID_ORDINAL);- fail("getParent for INVALID_ORDINAL should throw exception");- } catch (ArrayIndexOutOfBoundsException e) {- // ok- }- try {- int parent = tw.getParent(tr.getSize());- fail("getParent for getSize() should throw exception, but returned "- + parent);- } catch (ArrayIndexOutOfBoundsException e) {- // ok- }+ });+ expectThrows(ArrayIndexOutOfBoundsException.class, () -> {+ tw.getParent(tr.getSize());+ });}/**diff --git a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetAssociations.java b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetAssociations.javaindex a300e47bfb8..b065a8d54de 100644--- a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetAssociations.java+++ b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetAssociations.java@@ -142,19 +142,13 @@ public class TestTaxonomyFacetAssociations extends FacetTestCase {IndexSearcher searcher = newSearcher(reader);searcher.search(new MatchAllDocsQuery(), fc);Facets facets = new TaxonomyFacetSumFloatAssociations(taxoReader, config, fc);- try {+ expectThrows(IllegalArgumentException.class, () -> {facets.getSpecificValue("float");- fail("should have hit exc");- } catch (IllegalArgumentException iae) {- // expected- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {facets.getTopChildren(10, "float");- fail("should have hit exc");- } catch (IllegalArgumentException iae) {- // expected- }+ });}public void testMixedTypesInSameIndexField() throws Exception {@@ -168,12 +162,9 @@ public class TestTaxonomyFacetAssociations extends FacetTestCase {Document doc = new Document();doc.add(new IntAssociationFacetField(14, "a", "x"));doc.add(new FloatAssociationFacetField(55.0f, "b", "y"));- try {+ expectThrows(IllegalArgumentException.class, () -> {writer.addDocument(config.build(taxoWriter, doc));- fail("did not hit expected exception");- } catch (IllegalArgumentException exc) {- // expected- }+ });writer.close();IOUtils.close(taxoWriter, dir, taxoDir);}@@ -189,12 +180,10 @@ public class TestTaxonomyFacetAssociations extends FacetTestCase {Document doc = new Document();doc.add(new IntAssociationFacetField(14, "a", "x"));- try {+ expectThrows(IllegalArgumentException.class, () -> {writer.addDocument(config.build(taxoWriter, doc));- fail("did not hit expected exception");- } catch (IllegalArgumentException exc) {- // expected- }+ });+writer.close();IOUtils.close(taxoWriter, dir, taxoDir);}@@ -210,12 +199,10 @@ public class TestTaxonomyFacetAssociations extends FacetTestCase {Document doc = new Document();doc.add(new IntAssociationFacetField(14, "a", "x"));- try {+ expectThrows(IllegalArgumentException.class, () -> {writer.addDocument(config.build(taxoWriter, doc));- fail("did not hit expected exception");- } catch (IllegalArgumentException exc) {- // expected- }+ });+writer.close();IOUtils.close(taxoWriter, dir, taxoDir);}diff --git a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetCounts.java b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetCounts.javaindex 78787e4efcf..20bfdb5dc8e 100644--- a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetCounts.java+++ b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetCounts.java@@ -243,19 +243,13 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {List<FacetResult> results = facets.getAllDims(10);assertTrue(results.isEmpty());- try {+ expectThrows(IllegalArgumentException.class, () -> {facets.getSpecificValue("a");- fail("should have hit exc");- } catch (IllegalArgumentException iae) {- // expected- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {facets.getTopChildren(10, "a");- fail("should have hit exc");- } catch (IllegalArgumentException iae) {- // expected- }+ });writer.close();IOUtils.close(taxoWriter, searcher.getIndexReader(), taxoReader, taxoDir, dir);@@ -317,12 +311,9 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {searcher.search(new MatchAllDocsQuery(), c);Facets facets = getTaxonomyFacetCounts(taxoReader, config, c);- try {+ expectThrows(IllegalArgumentException.class, () -> {facets.getSpecificValue("a");- fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });FacetResult result = facets.getTopChildren(10, "a");assertEquals(1, result.labelValues.length);@@ -404,12 +395,9 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {assertEquals(1, facets.getTopChildren(10, "dim").value);assertEquals(1, facets.getTopChildren(10, "dim2").value);assertEquals(1, facets.getTopChildren(10, "dim3").value);- try {- assertEquals(1, facets.getSpecificValue("dim"));- fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ expectThrows(IllegalArgumentException.class, () -> {+ facets.getSpecificValue("dim");+ });assertEquals(1, facets.getSpecificValue("dim2"));assertEquals(1, facets.getSpecificValue("dim3"));writer.close();@@ -479,12 +467,10 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {Document doc = new Document();doc.add(newTextField("field", "text", Field.Store.NO));doc.add(new FacetField("a", "path", "other"));- try {+ expectThrows(IllegalArgumentException.class, () -> {config.build(taxoWriter, doc);- fail("did not hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+writer.close();IOUtils.close(taxoWriter, dir, taxoDir);}@@ -502,12 +488,10 @@ public class TestTaxonomyFacetCounts extends FacetTestCase {doc.add(newTextField("field", "text", Field.Store.NO));doc.add(new FacetField("a", "path"));doc.add(new FacetField("a", "path2"));- try {+ expectThrows(IllegalArgumentException.class, () -> {config.build(taxoWriter, doc);- fail("did not hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+writer.close();IOUtils.close(taxoWriter, dir, taxoDir);}diff --git a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetSumValueSource.java b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetSumValueSource.javaindex 09aa5df3ad7..0ad90bac9c5 100644--- a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetSumValueSource.java+++ b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/TestTaxonomyFacetSumValueSource.java@@ -229,19 +229,13 @@ public class TestTaxonomyFacetSumValueSource extends FacetTestCase {List<FacetResult> results = facets.getAllDims(10);assertTrue(results.isEmpty());- try {+ expectThrows(IllegalArgumentException.class, () -> {facets.getSpecificValue("a");- fail("should have hit exc");- } catch (IllegalArgumentException iae) {- // expected- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {facets.getTopChildren(10, "a");- fail("should have hit exc");- } catch (IllegalArgumentException iae) {- // expected- }+ });IOUtils.close(searcher.getIndexReader(), taxoReader, dir, taxoDir);}diff --git a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestDirectoryTaxonomyReader.java b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestDirectoryTaxonomyReader.javaindex 9b117c038e5..19820488fee 100644--- a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestDirectoryTaxonomyReader.java+++ b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestDirectoryTaxonomyReader.java@@ -110,12 +110,10 @@ public class TestDirectoryTaxonomyReader extends FacetTestCase {DirectoryTaxonomyReader ltr = new DirectoryTaxonomyReader(dir);ltr.close();- try {+ expectThrows(AlreadyClosedException.class, () -> {ltr.getSize();- fail("An AlreadyClosedException should have been thrown here");- } catch (AlreadyClosedException ace) {- // good!- }+ });+dir.close();}diff --git a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestDirectoryTaxonomyWriter.java b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestDirectoryTaxonomyWriter.javaindex 2e985988c29..2edee33fd7f 100644--- a/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestDirectoryTaxonomyWriter.java+++ b/lucene/facet/src/test/org/apache/lucene/facet/taxonomy/directory/TestDirectoryTaxonomyWriter.java@@ -134,13 +134,11 @@ public class TestDirectoryTaxonomyWriter extends FacetTestCase {DirectoryTaxonomyWriter dtw = new DirectoryTaxonomyWriter(dir);dtw.addCategory(new FacetLabel("a"));dtw.rollback();- try {+ // should not have succeeded to add a category following rollback.+ expectThrows(AlreadyClosedException.class, () -> {dtw.addCategory(new FacetLabel("a"));- fail("should not have succeeded to add a category following rollback.");- } catch (AlreadyClosedException e) {- // expected- }-+ });+dir.close();}@@ -162,12 +160,11 @@ public class TestDirectoryTaxonomyWriter extends FacetTestCase {Directory dir = newDirectory();DirectoryTaxonomyWriter dtw = new DirectoryTaxonomyWriter(dir);dtw.close();- try {+ // should not succeed to add a category following close.+ expectThrows(AlreadyClosedException.class, () -> {dtw.addCategory(new FacetLabel("a"));- fail("should not have succeeded to add a category following close.");- } catch (AlreadyClosedException e) {- // expected- }+ });+dir.close();}diff --git a/lucene/highlighter/src/test/org/apache/lucene/search/postingshighlight/TestPostingsHighlighter.java b/lucene/highlighter/src/test/org/apache/lucene/search/postingshighlight/TestPostingsHighlighter.javaindex 6574b6273a5..4b7e66bedb7 100644--- a/lucene/highlighter/src/test/org/apache/lucene/search/postingshighlight/TestPostingsHighlighter.java+++ b/lucene/highlighter/src/test/org/apache/lucene/search/postingshighlight/TestPostingsHighlighter.java@@ -405,19 +405,15 @@ public class TestPostingsHighlighter extends LuceneTestCase {Query query = new TermQuery(new Term("body", "test"));TopDocs topDocs = searcher.search(query, 10, Sort.INDEXORDER);assertEquals(2, topDocs.totalHits);- try {+ expectThrows(IllegalArgumentException.class, () -> {highlighter.highlight("body", query, searcher, topDocs, 2);- fail("did not hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });- try {+ expectThrows(IllegalArgumentException.class, () -> {highlighter.highlight("title", new TermQuery(new Term("title", "test")), searcher, topDocs, 2);fail("did not hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+ir.close();dir.close();}diff --git a/lucene/highlighter/src/test/org/apache/lucene/search/vectorhighlight/SimpleFragListBuilderTest.java b/lucene/highlighter/src/test/org/apache/lucene/search/vectorhighlight/SimpleFragListBuilderTest.javaindex f21e0dd70bb..98ec2d6e4c8 100644--- a/lucene/highlighter/src/test/org/apache/lucene/search/vectorhighlight/SimpleFragListBuilderTest.java+++ b/lucene/highlighter/src/test/org/apache/lucene/search/vectorhighlight/SimpleFragListBuilderTest.java@@ -28,13 +28,10 @@ public class SimpleFragListBuilderTest extends AbstractTestCase {}public void testTooSmallFragSize() throws Exception {- try{+ expectThrows(IllegalArgumentException.class, () -> {SimpleFragListBuilder sflb = new SimpleFragListBuilder();- sflb.createFieldFragList( fpl(new TermQuery(new Term(F, "a")), "b c d" ), sflb.minFragCharSize - 1 );- fail( "IllegalArgumentException must be thrown" );- }- catch ( IllegalArgumentException expected ) {- }+ sflb.createFieldFragList(fpl(new TermQuery(new Term(F, "a")), "b c d"), sflb.minFragCharSize - 1);+ });}public void testSmallerFragSizeThanTermQuery() throws Exception {diff --git a/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoin.java b/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoin.javaindex e331c8a2683..a1987744cae 100644--- a/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoin.java+++ b/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoin.java@@ -1458,12 +1458,10 @@ public class TestBlockJoin extends LuceneTestCase {ToParentBlockJoinCollector c = new ToParentBlockJoinCollector(new Sort(new SortField("parentID", SortField.Type.STRING)),10, true, true);- try {+ expectThrows(IllegalStateException.class, () -> {newSearcher(r).search(parentQuery.build(), c);- fail("should have hit exception");- } catch (IllegalStateException ise) {- // expected- }+ });+r.close();d.close();diff --git a/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoinValidation.java b/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoinValidation.javaindex 423188d64ca..565578ce295 100644--- a/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoinValidation.java+++ b/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoinValidation.java@@ -81,12 +81,10 @@ public class TestBlockJoinValidation extends LuceneTestCase {public void testNextDocValidationForToParentBjq() throws Exception {Query parentQueryWithRandomChild = createChildrenQueryWithOneParent(getRandomChildNumber(0));ToParentBlockJoinQuery blockJoinQuery = new ToParentBlockJoinQuery(parentQueryWithRandomChild, parentsFilter, ScoreMode.None);- try {+ IllegalStateException expected = expectThrows(IllegalStateException.class, () -> {indexSearcher.search(blockJoinQuery, 1);- fail("didn't get expected exception");- } catch (IllegalStateException expected) {- assertTrue(expected.getMessage() != null && expected.getMessage().contains("child query must only match non-parent docs"));- }+ });+ assertTrue(expected.getMessage() != null && expected.getMessage().contains("child query must only match non-parent docs"));}public void testAdvanceValidationForToParentBjq() throws Exception {@@ -102,12 +100,10 @@ public class TestBlockJoinValidation extends LuceneTestCase {conjunctionQuery.add(new BooleanClause(childQuery, BooleanClause.Occur.MUST));conjunctionQuery.add(new BooleanClause(blockJoinQuery, BooleanClause.Occur.MUST));- try {+ IllegalStateException expected = expectThrows(IllegalStateException.class, () -> {indexSearcher.search(conjunctionQuery.build(), 1);- fail("didn't get expected exception");- } catch (IllegalStateException expected) {- assertTrue(expected.getMessage() != null && expected.getMessage().contains("child query must only match non-parent docs"));- }+ });+ assertTrue(expected.getMessage() != null && expected.getMessage().contains("child query must only match non-parent docs"));}public void testNextDocValidationForToChildBjq() throws Exception {@@ -115,12 +111,10 @@ public class TestBlockJoinValidation extends LuceneTestCase {ToChildBlockJoinQuery blockJoinQuery = new ToChildBlockJoinQuery(parentQueryWithRandomChild, parentsFilter);- try {+ IllegalStateException expected = expectThrows(IllegalStateException.class, () -> {indexSearcher.search(blockJoinQuery, 1);- fail("didn't get expected exception");- } catch (IllegalStateException expected) {- assertTrue(expected.getMessage() != null && expected.getMessage().contains(ToChildBlockJoinQuery.INVALID_QUERY_MESSAGE));- }+ });+ assertTrue(expected.getMessage() != null && expected.getMessage().contains(ToChildBlockJoinQuery.INVALID_QUERY_MESSAGE));}public void testAdvanceValidationForToChildBjq() throws Exception {@@ -138,12 +132,11 @@ public class TestBlockJoinValidation extends LuceneTestCase {target = TestUtil.nextInt(random(), 0, context.reader().maxDoc() - 2);} while (parentDocs.get(target + 1));- try {- scorer.iterator().advance(target);- fail();- } catch (IllegalStateException expected) {- assertTrue(expected.getMessage() != null && expected.getMessage().contains(ToChildBlockJoinQuery.INVALID_QUERY_MESSAGE));- }+ final int illegalTarget = target;+ IllegalStateException expected = expectThrows(IllegalStateException.class, () -> {+ scorer.iterator().advance(illegalTarget);+ });+ assertTrue(expected.getMessage() != null && expected.getMessage().contains(ToChildBlockJoinQuery.INVALID_QUERY_MESSAGE));}private static List<Document> createDocsForSegment(int segmentNumber) {diff --git a/lucene/memory/src/test/org/apache/lucene/index/memory/TestMemoryIndex.java b/lucene/memory/src/test/org/apache/lucene/index/memory/TestMemoryIndex.javaindex c8b352af958..b150ea3e085 100644--- a/lucene/memory/src/test/org/apache/lucene/index/memory/TestMemoryIndex.java+++ b/lucene/memory/src/test/org/apache/lucene/index/memory/TestMemoryIndex.java@@ -70,21 +70,15 @@ public class TestMemoryIndex extends LuceneTestCase {// freeze!mi.freeze();- try {+ RuntimeException expected = expectThrows(RuntimeException.class, () -> {mi.addField("f3", "and yet more", analyzer);- fail("Expected an IllegalArgumentException when adding a field after calling freeze()");- }- catch (RuntimeException e) {- assertThat(e.getMessage(), containsString("frozen"));- }+ });+ assertThat(expected.getMessage(), containsString("frozen"));- try {+ expected = expectThrows(RuntimeException.class, () -> {mi.setSimilarity(new BM25Similarity(1, 1));- fail("Expected an IllegalArgumentException when setting the Similarity after calling freeze()");- }- catch (RuntimeException e) {- assertThat(e.getMessage(), containsString("frozen"));- }+ });+ assertThat(expected.getMessage(), containsString("frozen"));assertThat(mi.search(new TermQuery(new Term("f1", "some"))), not(is(0.0f)));diff --git a/lucene/misc/src/test/org/apache/lucene/index/SortingLeafReaderTest.java b/lucene/misc/src/test/org/apache/lucene/index/SortingLeafReaderTest.javaindex 6052ab53f1e..3e8cb99ae07 100644--- a/lucene/misc/src/test/org/apache/lucene/index/SortingLeafReaderTest.java+++ b/lucene/misc/src/test/org/apache/lucene/index/SortingLeafReaderTest.java@@ -64,12 +64,10 @@ public class SortingLeafReaderTest extends SorterTestBase {}public void testBadSort() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {SortingLeafReader.wrap(sortedReader, Sort.RELEVANCE);- fail("Didn't get expected exception");- } catch (IllegalArgumentException e) {- assertEquals("Cannot sort an index with a Sort that refers to the relevance score", e.getMessage());- }+ });+ assertEquals("Cannot sort an index with a Sort that refers to the relevance score", expected.getMessage());}}diff --git a/lucene/misc/src/test/org/apache/lucene/index/TestSortingMergePolicy.java b/lucene/misc/src/test/org/apache/lucene/index/TestSortingMergePolicy.javaindex a0c3fb1b3cf..a5486f4ce7e 100644--- a/lucene/misc/src/test/org/apache/lucene/index/TestSortingMergePolicy.java+++ b/lucene/misc/src/test/org/apache/lucene/index/TestSortingMergePolicy.java@@ -192,12 +192,10 @@ public class TestSortingMergePolicy extends BaseMergePolicyTestCase {}public void testBadSort() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new SortingMergePolicy(newMergePolicy(), Sort.RELEVANCE);- fail("Didn't get expected exception");- } catch (IllegalArgumentException e) {- assertEquals("Cannot sort an index with a Sort that refers to the relevance score", e.getMessage());- }+ });+ assertEquals("Cannot sort an index with a Sort that refers to the relevance score", expected.getMessage());}}diff --git a/lucene/misc/src/test/org/apache/lucene/uninverting/TestFieldCache.java b/lucene/misc/src/test/org/apache/lucene/uninverting/TestFieldCache.javaindex 215e9a353e7..fb0587595e0 100644--- a/lucene/misc/src/test/org/apache/lucene/uninverting/TestFieldCache.java+++ b/lucene/misc/src/test/org/apache/lucene/uninverting/TestFieldCache.java@@ -440,43 +440,37 @@ public class TestFieldCache extends LuceneTestCase {LeafReader ar = getOnlySegmentReader(ir);// Binary type: can be retrieved via getTerms()- try {+ expectThrows(IllegalStateException.class, () -> {FieldCache.DEFAULT.getNumerics(ar, "binary", FieldCache.NUMERIC_UTILS_INT_PARSER, false);- fail();- } catch (IllegalStateException expected) {}+ });BinaryDocValues binary = FieldCache.DEFAULT.getTerms(ar, "binary", true);final BytesRef term = binary.get(0);assertEquals("binary value", term.utf8ToString());- try {+ expectThrows(IllegalStateException.class, () -> {FieldCache.DEFAULT.getTermsIndex(ar, "binary");- fail();- } catch (IllegalStateException expected) {}+ });- try {+ expectThrows(IllegalStateException.class, () -> {FieldCache.DEFAULT.getDocTermOrds(ar, "binary", null);- fail();- } catch (IllegalStateException expected) {}+ });- try {+ expectThrows(IllegalStateException.class, () -> {new DocTermOrds(ar, null, "binary");- fail();- } catch (IllegalStateException expected) {}+ });Bits bits = FieldCache.DEFAULT.getDocsWithField(ar, "binary");assertTrue(bits.get(0));// Sorted type: can be retrieved via getTerms(), getTermsIndex(), getDocTermOrds()- try {+ expectThrows(IllegalStateException.class, () -> {FieldCache.DEFAULT.getNumerics(ar, "sorted", FieldCache.NUMERIC_UTILS_INT_PARSER, false);- fail();- } catch (IllegalStateException expected) {}+ });- try {+ expectThrows(IllegalStateException.class, () -> {new DocTermOrds(ar, null, "sorted");- fail();- } catch (IllegalStateException expected) {}+ });binary = FieldCache.DEFAULT.getTerms(ar, "sorted", true);BytesRef scratch = binary.get(0);@@ -501,49 +495,41 @@ public class TestFieldCache extends LuceneTestCase {NumericDocValues numeric = FieldCache.DEFAULT.getNumerics(ar, "numeric", FieldCache.NUMERIC_UTILS_INT_PARSER, false);assertEquals(42, numeric.get(0));- try {+ expectThrows(IllegalStateException.class, () -> {FieldCache.DEFAULT.getTerms(ar, "numeric", true);- fail();- } catch (IllegalStateException expected) {}+ });- try {+ expectThrows(IllegalStateException.class, () -> {FieldCache.DEFAULT.getTermsIndex(ar, "numeric");- fail();- } catch (IllegalStateException expected) {}+ });- try {+ expectThrows(IllegalStateException.class, () -> {FieldCache.DEFAULT.getDocTermOrds(ar, "numeric", null);- fail();- } catch (IllegalStateException expected) {}+ });- try {+ expectThrows(IllegalStateException.class, () -> {new DocTermOrds(ar, null, "numeric");- fail();- } catch (IllegalStateException expected) {}+ });bits = FieldCache.DEFAULT.getDocsWithField(ar, "numeric");assertTrue(bits.get(0));// SortedSet type: can be retrieved via getDocTermOrds()- try {+ expectThrows(IllegalStateException.class, () -> {FieldCache.DEFAULT.getNumerics(ar, "sortedset", FieldCache.NUMERIC_UTILS_INT_PARSER, false);- fail();- } catch (IllegalStateException expected) {}+ });- try {+ expectThrows(IllegalStateException.class, () -> {FieldCache.DEFAULT.getTerms(ar, "sortedset", true);- fail();- } catch (IllegalStateException expected) {}+ });- try {+ expectThrows(IllegalStateException.class, () -> {FieldCache.DEFAULT.getTermsIndex(ar, "sortedset");- fail();- } catch (IllegalStateException expected) {}+ });- try {+ expectThrows(IllegalStateException.class, () -> {new DocTermOrds(ar, null, "sortedset");- fail();- } catch (IllegalStateException expected) {}+ });sortedSet = FieldCache.DEFAULT.getDocTermOrds(ar, "sortedset", null);sortedSet.setDocument(0);diff --git a/lucene/misc/src/test/org/apache/lucene/uninverting/TestFieldCacheSort.java b/lucene/misc/src/test/org/apache/lucene/uninverting/TestFieldCacheSort.javaindex 55d6714b1ad..717d36424e5 100644--- a/lucene/misc/src/test/org/apache/lucene/uninverting/TestFieldCacheSort.java+++ b/lucene/misc/src/test/org/apache/lucene/uninverting/TestFieldCacheSort.java@@ -1033,10 +1033,9 @@ public class TestFieldCacheSort extends LuceneTestCase {IndexReader reader = UninvertingReader.wrap(DirectoryReader.open(indexStore),Collections.singletonMap("string", Type.SORTED));IndexSearcher searcher = new IndexSearcher(reader);- try {+ expectThrows(IllegalStateException.class, () -> {searcher.search(new MatchAllDocsQuery(), 500, sort);- fail("didn't get expected exception");- } catch (IllegalStateException expected) {}+ });reader.close();indexStore.close();}diff --git a/lucene/queries/src/test/org/apache/lucene/queries/CommonTermsQueryTest.java b/lucene/queries/src/test/org/apache/lucene/queries/CommonTermsQueryTest.javaindex 640089add39..a7bfffdfc61 100644--- a/lucene/queries/src/test/org/apache/lucene/queries/CommonTermsQueryTest.java+++ b/lucene/queries/src/test/org/apache/lucene/queries/CommonTermsQueryTest.java@@ -179,12 +179,10 @@ public class CommonTermsQueryTest extends LuceneTestCase {Random random = random();CommonTermsQuery query = new CommonTermsQuery(randomOccur(random),randomOccur(random), random().nextFloat());- try {+ // null values are not supported+ expectThrows(IllegalArgumentException.class, () -> {query.add(null);- fail("null values are not supported");- } catch (IllegalArgumentException ex) {-- }+ });}public void testMinShouldMatch() throws IOException {@@ -324,23 +322,19 @@ public class CommonTermsQueryTest extends LuceneTestCase {IOUtils.close(r, w, dir, analyzer);}+ /** MUST_NOT is not supported */public void testIllegalOccur() {Random random = random();- try {+ expectThrows(IllegalArgumentException.class, () -> {new CommonTermsQuery(Occur.MUST_NOT, randomOccur(random), random().nextFloat());- fail("MUST_NOT is not supproted");- } catch (IllegalArgumentException ex) {+ });- }- try {+ expectThrows(IllegalArgumentException.class, () -> {new CommonTermsQuery(randomOccur(random), Occur.MUST_NOT, random().nextFloat());- fail("MUST_NOT is not supproted");- } catch (IllegalArgumentException ex) {-- }+ });}@Testdiff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/analyzing/TestAnalyzingQueryParser.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/analyzing/TestAnalyzingQueryParser.javaindex 2f72e070aeb..bf5f69f7b61 100644--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/analyzing/TestAnalyzingQueryParser.java+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/analyzing/TestAnalyzingQueryParser.java@@ -102,52 +102,31 @@ public class TestAnalyzingQueryParser extends LuceneTestCase {}public void testSingleChunkExceptions() {- boolean ex = false;String termStr = "the*tre";Analyzer stopsAnalyzer = new MockAnalyzer(random(), MockTokenizer.WHITESPACE, true, MockTokenFilter.ENGLISH_STOPSET);- try {- String q = parseWithAnalyzingQueryParser(termStr, stopsAnalyzer, true);- } catch (ParseException e){- if (e.getMessage().contains("returned nothing")){- ex = true;- }- }- assertEquals("Should have returned nothing", true, ex);- ex = false;++ ParseException expected = expectThrows(ParseException.class, () -> {+ parseWithAnalyzingQueryParser(termStr, stopsAnalyzer, true);+ });+ assertTrue(expected.getMessage().contains("returned nothing"));AnalyzingQueryParser qp = new AnalyzingQueryParser(FIELD, a);- try{+ expected = expectThrows(ParseException.class, () -> {qp.analyzeSingleChunk(FIELD, "", "not a single chunk");- } catch (ParseException e){- if (e.getMessage().contains("multiple terms")){- ex = true;- }- }- assertEquals("Should have produced multiple terms", true, ex);+ });+ assertTrue(expected.getMessage().contains("multiple terms"));}public void testWildcardAlone() throws ParseException {//seems like crazy edge case, but can be useful in concordance- boolean pex = false;- try{- Query q = getAnalyzedQuery("*", a, false);- } catch (ParseException e){- pex = true;- }- assertEquals("Wildcard alone with allowWildcard=false", true, pex);+ expectThrows(ParseException.class, () -> {+ getAnalyzedQuery("*", a, false);+ });- pex = false;- try {- String qString = parseWithAnalyzingQueryParser("*", a, true);- assertEquals("Every word", "*", qString);- } catch (ParseException e){- pex = true;- }-- assertEquals("Wildcard alone with allowWildcard=true", false, pex);-+ String qString = parseWithAnalyzingQueryParser("*", a, true);+ assertEquals("Every word", "*", qString);}public void testWildCardEscapes() throws ParseException, IOException {@@ -162,15 +141,9 @@ public class TestAnalyzingQueryParser extends LuceneTestCase {}public void testWildCardQueryNoLeadingAllowed() {- boolean ex = false;- try{- String q = parseWithAnalyzingQueryParser(wildcardInput[0], a, false);-- } catch (ParseException e){- ex = true;- }- assertEquals("Testing initial wildcard not allowed",- true, ex);+ expectThrows(ParseException.class, () -> {+ parseWithAnalyzingQueryParser(wildcardInput[0], a, false);+ });}public void testWildCardQuery() throws ParseException {diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestMultiFieldQueryParser.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestMultiFieldQueryParser.javaindex 4e7cb545151..d4d8b9336d1 100644--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestMultiFieldQueryParser.java+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestMultiFieldQueryParser.java@@ -177,12 +177,10 @@ public class TestMultiFieldQueryParser extends LuceneTestCase {assertEquals("(b:one +b:more) (+t:two)", q.toString());String[] queries5 = {"blah"};- try {- q = MultiFieldQueryParser.parse(queries5, fields, new MockAnalyzer(random()));- fail();- } catch(IllegalArgumentException e) {- // expected exception, array length differs- }+ // expected exception, array length differs+ expectThrows(IllegalArgumentException.class, () -> {+ MultiFieldQueryParser.parse(queries5, fields, new MockAnalyzer(random()));+ });// check also with stop words for this static form (qtxts[], fields[]).TestQueryParser.QPTestAnalyzer stopA = new TestQueryParser.QPTestAnalyzer();@@ -206,13 +204,11 @@ public class TestMultiFieldQueryParser extends LuceneTestCase {q = MultiFieldQueryParser.parse("one two", fields, flags, new MockAnalyzer(random()));assertEquals("+(b:one b:two) -(t:one t:two)", q.toString());- try {+ // expected exception, array length differs+ expectThrows(IllegalArgumentException.class, () -> {BooleanClause.Occur[] flags2 = {BooleanClause.Occur.MUST};- q = MultiFieldQueryParser.parse("blah", fields, flags2, new MockAnalyzer(random()));- fail();- } catch(IllegalArgumentException e) {- // expected exception, array length differs- }+ MultiFieldQueryParser.parse("blah", fields, flags2, new MockAnalyzer(random()));+ });}public void testStaticMethod2Old() throws ParseException {@@ -226,13 +222,11 @@ public class TestMultiFieldQueryParser extends LuceneTestCase {q = MultiFieldQueryParser.parse("one two", fields, flags, new MockAnalyzer(random()));assertEquals("+(b:one b:two) -(t:one t:two)", q.toString());- try {+ // expected exception, array length differs+ expectThrows(IllegalArgumentException.class, () -> {BooleanClause.Occur[] flags2 = {BooleanClause.Occur.MUST};- q = MultiFieldQueryParser.parse("blah", fields, flags2, new MockAnalyzer(random()));- fail();- } catch(IllegalArgumentException e) {- // expected exception, array length differs- }+ MultiFieldQueryParser.parse("blah", fields, flags2, new MockAnalyzer(random()));+ });}public void testStaticMethod3() throws ParseException {@@ -243,13 +237,11 @@ public class TestMultiFieldQueryParser extends LuceneTestCase {Query q = MultiFieldQueryParser.parse(queries, fields, flags, new MockAnalyzer(random()));assertEquals("+f1:one -f2:two f3:three", q.toString());- try {+ // expected exception, array length differs+ expectThrows(IllegalArgumentException.class, () -> {BooleanClause.Occur[] flags2 = {BooleanClause.Occur.MUST};- q = MultiFieldQueryParser.parse(queries, fields, flags2, new MockAnalyzer(random()));- fail();- } catch(IllegalArgumentException e) {- // expected exception, array length differs- }+ MultiFieldQueryParser.parse(queries, fields, flags2, new MockAnalyzer(random()));+ });}public void testStaticMethod3Old() throws ParseException {@@ -259,13 +251,11 @@ public class TestMultiFieldQueryParser extends LuceneTestCase {Query q = MultiFieldQueryParser.parse(queries, fields, flags, new MockAnalyzer(random()));assertEquals("+b:one -t:two", q.toString());- try {+ // expected exception, array length differs+ expectThrows(IllegalArgumentException.class, () -> {BooleanClause.Occur[] flags2 = {BooleanClause.Occur.MUST};- q = MultiFieldQueryParser.parse(queries, fields, flags2, new MockAnalyzer(random()));- fail();- } catch(IllegalArgumentException e) {- // expected exception, array length differs- }+ MultiFieldQueryParser.parse(queries, fields, flags2, new MockAnalyzer(random()));+ });}public void testAnalyzerReturningNull() throws ParseException {diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestQueryParser.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestQueryParser.javaindex 5d3b7ecf82b..2457d3ca81f 100644--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestQueryParser.java+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/classic/TestQueryParser.java@@ -259,24 +259,20 @@ public class TestQueryParser extends QueryParserTestBase {}+ // Wildcard queries should not be allowedpublic void testCustomQueryParserWildcard() {- try {+ expectThrows(ParseException.class, () -> {new QPTestParser("contents", new MockAnalyzer(random(),MockTokenizer.WHITESPACE, false)).parse("a?t");- fail("Wildcard queries should not be allowed");- } catch (ParseException expected) {- // expected exception- }+ });}+ // Fuzzy queries should not be allowedpublic void testCustomQueryParserFuzzy() throws Exception {- try {+ expectThrows(ParseException.class, () -> {new QPTestParser("contents", new MockAnalyzer(random(),MockTokenizer.WHITESPACE, false)).parse("xunit~");- fail("Fuzzy queries should not be allowed");- } catch (ParseException expected) {- // expected exception- }+ });}/** query parser that doesn't expand synonyms when users use double quotes */@@ -481,11 +477,8 @@ public class TestQueryParser extends QueryParserTestBase {public void testWildcardMaxDeterminizedStates() throws Exception {QueryParser qp = new QueryParser("field", new MockAnalyzer(random()));qp.setMaxDeterminizedStates(10);- try {+ expectThrows(TooComplexToDeterminizeException.class, () -> {qp.parse("a*aaaaaaa");- fail("should have hit exception");- } catch (TooComplexToDeterminizeException tctde) {- // expected- }+ });}}diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/complexPhrase/TestComplexPhraseQuery.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/complexPhrase/TestComplexPhraseQuery.javaindex 45d13de9b98..66078b0b499 100644--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/complexPhrase/TestComplexPhraseQuery.java+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/complexPhrase/TestComplexPhraseQuery.java@@ -86,14 +86,9 @@ public class TestComplexPhraseQuery extends LuceneTestCase {private void checkBadQuery(String qString) {ComplexPhraseQueryParser qp = new ComplexPhraseQueryParser(defaultFieldName, analyzer);qp.setInOrder(inOrder);- Throwable expected = null;- try {+ expectThrows(Throwable.class, () -> {qp.parse(qString);- } catch (Throwable e) {- expected = e;- }- assertNotNull("Expected parse error in " + qString, expected);-+ });}private void checkMatches(String qString, String expectedVals)diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/ext/TestExtendableQueryParser.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/ext/TestExtendableQueryParser.javaindex ac469308496..785dd1c23dc 100644--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/ext/TestExtendableQueryParser.java+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/ext/TestExtendableQueryParser.java@@ -57,11 +57,9 @@ public class TestExtendableQueryParser extends TestQueryParser {Extensions ext = newExtensions(':');ext.add("testExt", new ExtensionStub());ExtendableQueryParser parser = (ExtendableQueryParser) getParser(null, ext);- try {+ expectThrows(ParseException.class, () -> {parser.parse("aField:testExt:\"foo \\& bar\"");- fail("extension field delimiter is not escaped");- } catch (ParseException e) {- }+ });}public void testExtFieldUnqoted() throws Exception {diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/ext/TestExtensions.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/ext/TestExtensions.javaindex fde11bbbb0f..7899d501cb9 100644--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/ext/TestExtensions.java+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/ext/TestExtensions.java@@ -68,11 +68,9 @@ public class TestExtensions extends LuceneTestCase {public void testEscapeExtension() {assertEquals("abc\\:\\?\\{\\}\\[\\]\\\\\\(\\)\\+\\-\\!\\~", ext.escapeExtensionField("abc:?{}[]\\()+-!~"));- try {+ // should throw NPE - escape string is null+ expectThrows(NullPointerException.class, () -> {ext.escapeExtensionField(null);- fail("should throw NPE - escape string is null");- } catch (NullPointerException e) {- //- }+ });}}diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/precedence/TestPrecedenceQueryParser.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/precedence/TestPrecedenceQueryParser.javaindex 4dbe3f9e0d7..b58cede60db 100644--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/precedence/TestPrecedenceQueryParser.java+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/precedence/TestPrecedenceQueryParser.java@@ -314,12 +314,9 @@ public class TestPrecedenceQueryParser extends LuceneTestCase {fq = (FuzzyQuery) getQuery("term~", null);assertEquals(2, fq.getMaxEdits());assertEquals(FuzzyQuery.defaultPrefixLength, fq.getPrefixLength());- try {+ expectThrows(ParseException.class, () -> {getQuery("term~1.1", null); // value > 1, throws exception- fail();- } catch (ParseException pe) {- // expected exception- }+ });assertTrue(getQuery("term*germ", null) instanceof WildcardQuery);/*@@ -580,21 +577,17 @@ public class TestPrecedenceQueryParser extends LuceneTestCase {}public void testException() throws Exception {- try {+ expectThrows(QueryNodeParseException.class, () -> {assertQueryEquals("\"some phrase", null, "abc");- fail("ParseException expected, not thrown");- } catch (QueryNodeParseException expected) {- }+ });}+ // ParseException expected due to too many boolean clausespublic void testBooleanQuery() throws Exception {BooleanQuery.setMaxClauseCount(2);- try {+ expectThrows(QueryNodeException.class, () -> {getParser(new MockAnalyzer(random(), MockTokenizer.WHITESPACE, false)).parse("one two three", "field");- fail("ParseException expected due to too many boolean clauses");- } catch (QueryNodeException expected) {- // too many boolean clauses, so ParseException is expected- }+ });}// LUCENE-792diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/spans/TestSpanQueryParser.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/spans/TestSpanQueryParser.javaindex 192cd3bbffe..0bcfedf067c 100644--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/spans/TestSpanQueryParser.java+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/spans/TestSpanQueryParser.java@@ -168,62 +168,33 @@ public class TestSpanQueryParser extends LuceneTestCase {public void testQueryValidator() throws QueryNodeException {- try {- getSpanQuery("term*");- fail("QueryNodeException was expected, wildcard queries should not be supported");+ expectThrows(QueryNodeException.class, () -> {+ getSpanQuery("term*"); // wildcard queries should not be supported+ });- } catch (QueryNodeException ex) {- // expected exception- }+ expectThrows(QueryNodeException.class, () -> {+ getSpanQuery("[a TO z]"); // range queries should not be supported+ });- try {- getSpanQuery("[a TO z]");- fail("QueryNodeException was expected, range queries should not be supported");+ expectThrows(QueryNodeException.class, () -> {+ getSpanQuery("a~0.5"); // boost queries should not be supported+ });- } catch (QueryNodeException ex) {- // expected exception- }+ expectThrows(QueryNodeException.class, () -> {+ getSpanQuery("a^0.5"); // fuzzy queries should not be supported+ });- try {- getSpanQuery("a~0.5");- fail("QueryNodeException was expected, boost queries should not be supported");+ expectThrows(QueryNodeException.class, () -> {+ getSpanQuery("\"a b\""); // quoted queries should not be supported+ });- } catch (QueryNodeException ex) {- // expected exception- }-- try {- getSpanQuery("a^0.5");- fail("QueryNodeException was expected, fuzzy queries should not be supported");-- } catch (QueryNodeException ex) {- // expected exception- }-- try {- getSpanQuery("\"a b\"");- fail("QueryNodeException was expected, quoted queries should not be supported");-- } catch (QueryNodeException ex) {- // expected exception- }-- try {- getSpanQuery("(a b)");- fail("QueryNodeException was expected, parenthesized queries should not be supported");-- } catch (QueryNodeException ex) {- // expected exception- }-- try {- getSpanQuery("a AND b");- fail("QueryNodeException was expected, and queries should not be supported");-- } catch (QueryNodeException ex) {- // expected exception- }+ expectThrows(QueryNodeException.class, () -> {+ getSpanQuery("(a b)"); // parenthesized queries should not be supported+ });+ expectThrows(QueryNodeException.class, () -> {+ getSpanQuery("a AND b"); // AND queries should not be supported+ });}}diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestMultiFieldQPHelper.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestMultiFieldQPHelper.javaindex 0988e56d7da..28e815dfd1c 100644--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestMultiFieldQPHelper.java+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestMultiFieldQPHelper.java@@ -195,12 +195,10 @@ public class TestMultiFieldQPHelper extends LuceneTestCase {assertEquals("(b:one +b:more) t:two", q.toString());String[] queries5 = { "blah" };- try {- q = QueryParserUtil.parse(queries5, fields, new MockAnalyzer(random()));- fail();- } catch (IllegalArgumentException e) {- // expected exception, array length differs- }+ // expected exception, array length differs+ expectThrows(IllegalArgumentException.class, () -> {+ QueryParserUtil.parse(queries5, fields, new MockAnalyzer(random()));+ });// check also with stop words for this static form (qtxts[], fields[]).TestQPHelper.QPTestAnalyzer stopA = new TestQPHelper.QPTestAnalyzer();@@ -226,13 +224,11 @@ public class TestMultiFieldQPHelper extends LuceneTestCase {q = QueryParserUtil.parse("one two", fields, flags, new MockAnalyzer(random()));assertEquals("+(b:one b:two) -(t:one t:two)", q.toString());- try {+ // expected exception, array length differs+ expectThrows(IllegalArgumentException.class, () -> {BooleanClause.Occur[] flags2 = { BooleanClause.Occur.MUST };- q = QueryParserUtil.parse("blah", fields, flags2, new MockAnalyzer(random()));- fail();- } catch (IllegalArgumentException e) {- // expected exception, array length differs- }+ QueryParserUtil.parse("blah", fields, flags2, new MockAnalyzer(random()));+ });}public void testStaticMethod2Old() throws QueryNodeException {@@ -251,13 +247,11 @@ public class TestMultiFieldQPHelper extends LuceneTestCase {q = QueryParserUtil.parse("one two", fields, flags, new MockAnalyzer(random()));assertEquals("+(b:one b:two) -(t:one t:two)", q.toString());- try {+ // expected exception, array length differs+ expectThrows(IllegalArgumentException.class, () -> {BooleanClause.Occur[] flags2 = { BooleanClause.Occur.MUST };- q = QueryParserUtil.parse("blah", fields, flags2, new MockAnalyzer(random()));- fail();- } catch (IllegalArgumentException e) {- // expected exception, array length differs- }+ QueryParserUtil.parse("blah", fields, flags2, new MockAnalyzer(random()));+ });}public void testStaticMethod3() throws QueryNodeException {@@ -269,14 +263,12 @@ public class TestMultiFieldQPHelper extends LuceneTestCase {new MockAnalyzer(random()));assertEquals("+f1:one -f2:two f3:three", q.toString());- try {+ // expected exception, array length differs+ expectThrows(IllegalArgumentException.class, () -> {BooleanClause.Occur[] flags2 = { BooleanClause.Occur.MUST };- q = QueryParserUtil+ QueryParserUtil.parse(queries, fields, flags2, new MockAnalyzer(random()));- fail();- } catch (IllegalArgumentException e) {- // expected exception, array length differs- }+ });}public void testStaticMethod3Old() throws QueryNodeException {@@ -288,14 +280,12 @@ public class TestMultiFieldQPHelper extends LuceneTestCase {new MockAnalyzer(random()));assertEquals("+b:one -t:two", q.toString());- try {+ // expected exception, array length differs+ expectThrows(IllegalArgumentException.class, () -> {BooleanClause.Occur[] flags2 = { BooleanClause.Occur.MUST };- q = QueryParserUtil+ QueryParserUtil.parse(queries, fields, flags2, new MockAnalyzer(random()));- fail();- } catch (IllegalArgumentException e) {- // expected exception, array length differs- }+ });}public void testAnalyzerReturningNull() throws QueryNodeException {diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestQPHelper.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestQPHelper.javaindex 1c53726a3a3..e7d0c896e9a 100644--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestQPHelper.java+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestQPHelper.java@@ -619,18 +619,14 @@ public class TestQPHelper extends LuceneTestCase {assertWildcardQueryEquals("[A TO C]", true, "[a TO c]");assertWildcardQueryEquals("[A TO C]", false, "[A TO C]");// Test suffix queries: first disallow- try {+ expectThrows(QueryNodeException.class, () -> {assertWildcardQueryEquals("*Term", true, "*term");- fail();- } catch (QueryNodeException pe) {- // expected exception- }- try {+ });++ expectThrows(QueryNodeException.class, () -> {assertWildcardQueryEquals("?Term", true, "?term");- fail();- } catch (QueryNodeException pe) {- // expected exception- }+ });+// Test suffix queries: then allowassertWildcardQueryEquals("*Term", true, "*term", true);assertWildcardQueryEquals("?Term", true, "?term", true);@@ -1001,12 +997,9 @@ public class TestQPHelper extends LuceneTestCase {}public void assertQueryNodeException(String queryString) throws Exception {- try {+ expectThrows(QueryNodeException.class, () -> {getQuery(queryString, null);- } catch (QueryNodeException expected) {- return;- }- fail("ParseException expected, not thrown");+ });}public void testException() throws Exception {@@ -1019,35 +1012,29 @@ public class TestQPHelper extends LuceneTestCase {assertQueryNodeException("secret AND illegal) AND access:confidential");}+ // Wildcard queries should not be allowedpublic void testCustomQueryParserWildcard() {- try {+ expectThrows(QueryNodeException.class, () -> {new QPTestParser(new MockAnalyzer(random(), MockTokenizer.WHITESPACE, false)).parse("a?t", "contents");- fail("Wildcard queries should not be allowed");- } catch (QueryNodeException expected) {- // expected exception- }+ });}+ // Fuzzy queries should not be allowed"public void testCustomQueryParserFuzzy() throws Exception {- try {+ expectThrows(QueryNodeException.class, () -> {new QPTestParser(new MockAnalyzer(random(), MockTokenizer.WHITESPACE, false)).parse("xunit~", "contents");- fail("Fuzzy queries should not be allowed");- } catch (QueryNodeException expected) {- // expected exception- }+ });}+ // too many boolean clauses, so ParseException is expectedpublic void testBooleanQuery() throws Exception {BooleanQuery.setMaxClauseCount(2);- try {+ expectThrows(QueryNodeException.class, () -> {StandardQueryParser qp = new StandardQueryParser();qp.setAnalyzer(new MockAnalyzer(random(), MockTokenizer.WHITESPACE, false));qp.parse("one two three", "field");- fail("ParseException expected due to too many boolean clauses");- } catch (QueryNodeException expected) {- // too many boolean clauses, so ParseException is expected- }+ });}/**diff --git a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestStandardQP.java b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestStandardQP.javaindex 1bbdb53bb42..cc2ac12d7fc 100644--- a/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestStandardQP.java+++ b/lucene/queryparser/src/test/org/apache/lucene/queryparser/flexible/standard/TestStandardQP.java@@ -155,22 +155,18 @@ public class TestStandardQP extends QueryParserTestBase {@Overridepublic void testCollatedRange() throws Exception {- try {+ expectThrows(UnsupportedOperationException.class, () -> {setAnalyzeRangeTerms(getParser(null), true);super.testCollatedRange();- } catch (UnsupportedOperationException e) {- // expected- }+ });}@Overridepublic void testAutoGeneratePhraseQueriesOn() throws Exception {- try {+ expectThrows(UnsupportedOperationException.class, () -> {setAutoGeneratePhraseQueries(getParser(null), true);super.testAutoGeneratePhraseQueriesOn();- } catch (UnsupportedOperationException e) {- // expected- }+ });}@Overridediff --git a/lucene/replicator/src/test/org/apache/lucene/replicator/IndexAndTaxonomyRevisionTest.java b/lucene/replicator/src/test/org/apache/lucene/replicator/IndexAndTaxonomyRevisionTest.javaindex 88040047f07..022298b3026 100644--- a/lucene/replicator/src/test/org/apache/lucene/replicator/IndexAndTaxonomyRevisionTest.java+++ b/lucene/replicator/src/test/org/apache/lucene/replicator/IndexAndTaxonomyRevisionTest.java@@ -56,15 +56,13 @@ public class IndexAndTaxonomyRevisionTest extends ReplicatorTestCase {Directory taxoDir = newDirectory();SnapshotDirectoryTaxonomyWriter taxoWriter = new SnapshotDirectoryTaxonomyWriter(taxoDir);- try {- assertNotNull(new IndexAndTaxonomyRevision(indexWriter, taxoWriter));- fail("should have failed when there are no commits to snapshot");- } catch (IllegalStateException e) {- // expected- } finally {- indexWriter.close();- IOUtils.close(taxoWriter, taxoDir, indexDir);- }+ // should fail when there are no commits to snapshot+ expectThrows(IllegalStateException.class, () -> {+ new IndexAndTaxonomyRevision(indexWriter, taxoWriter);+ });++ indexWriter.close();+ IOUtils.close(taxoWriter, taxoDir, indexDir);}@Testdiff --git a/lucene/replicator/src/test/org/apache/lucene/replicator/IndexRevisionTest.java b/lucene/replicator/src/test/org/apache/lucene/replicator/IndexRevisionTest.javaindex d5f3588e8bc..77f323da004 100644--- a/lucene/replicator/src/test/org/apache/lucene/replicator/IndexRevisionTest.java+++ b/lucene/replicator/src/test/org/apache/lucene/replicator/IndexRevisionTest.java@@ -41,15 +41,13 @@ public class IndexRevisionTest extends ReplicatorTestCase {IndexWriterConfig conf = new IndexWriterConfig(null);conf.setIndexDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy());IndexWriter writer = new IndexWriter(dir, conf);- try {- assertNotNull(new IndexRevision(writer));- fail("should have failed when IndexDeletionPolicy is not Snapshot");- } catch (IllegalArgumentException e) {- // expected- } finally {- writer.close();- IOUtils.close(dir);- }+ // should fail when IndexDeletionPolicy is not Snapshot+ expectThrows(IllegalArgumentException.class, () -> {+ new IndexRevision(writer);+ });++ writer.close();+ IOUtils.close(dir);}@Test@@ -58,15 +56,13 @@ public class IndexRevisionTest extends ReplicatorTestCase {IndexWriterConfig conf = new IndexWriterConfig(null);conf.setIndexDeletionPolicy(new SnapshotDeletionPolicy(conf.getIndexDeletionPolicy()));IndexWriter writer = new IndexWriter(dir, conf);- try {- assertNotNull(new IndexRevision(writer));- fail("should have failed when there are no commits to snapshot");- } catch (IllegalStateException e) {- // expected- } finally {- writer.close();- IOUtils.close(dir);- }+ // should fail when there are no commits to snapshot"+ expectThrows(IllegalStateException.class, () -> {+ new IndexRevision(writer);+ });++ writer.close();+ IOUtils.close(dir);}@Testdiff --git a/lucene/replicator/src/test/org/apache/lucene/replicator/LocalReplicatorTest.java b/lucene/replicator/src/test/org/apache/lucene/replicator/LocalReplicatorTest.javaindex 2d32878d351..af23da1e0d3 100644--- a/lucene/replicator/src/test/org/apache/lucene/replicator/LocalReplicatorTest.java+++ b/lucene/replicator/src/test/org/apache/lucene/replicator/LocalReplicatorTest.java@@ -86,34 +86,25 @@ public class LocalReplicatorTest extends ReplicatorTestCase {assertEquals(1, res.sourceFiles.size());Entry<String,List<RevisionFile>> entry = res.sourceFiles.entrySet().iterator().next();replicator.close();- try {+ expectThrows(AlreadyClosedException.class, () -> {replicator.obtainFile(res.id, entry.getKey(), entry.getValue().get(0).fileName);- fail("should have failed on AlreadyClosedException");- } catch (AlreadyClosedException e) {- // expected- }+ });}@Testpublic void testPublishAlreadyClosed() throws IOException {replicator.close();- try {+ expectThrows(AlreadyClosedException.class, () -> {replicator.publish(createRevision(2));- fail("should have failed on AlreadyClosedException");- } catch (AlreadyClosedException e) {- // expected- }+ });}@Testpublic void testUpdateAlreadyClosed() throws IOException {replicator.close();- try {+ expectThrows(AlreadyClosedException.class, () -> {replicator.checkForUpdate(null);- fail("should have failed on AlreadyClosedException");- } catch (AlreadyClosedException e) {- // expected- }+ });}@Test@@ -140,12 +131,10 @@ public class LocalReplicatorTest extends ReplicatorTestCase {replicator.publish(createRevision(1));Revision old = new IndexRevision(sourceWriter);replicator.publish(createRevision(2));- try {+ // should fail to publish an older revision+ expectThrows(IllegalArgumentException.class, () -> {replicator.publish(old);- fail("should have failed to publish an older revision");- } catch (IllegalArgumentException e) {- // expected- }+ });assertEquals(1, DirectoryReader.listCommits(sourceDir).size());}@@ -167,12 +156,10 @@ public class LocalReplicatorTest extends ReplicatorTestCase {SessionToken session = replicator.checkForUpdate(null);replicator.setExpirationThreshold(5); // expire quicklyThread.sleep(50); // sufficient for expiration- try {+ // should fail to obtain a file for an expired session+ expectThrows(SessionExpiredException.class, () -> {replicator.obtainFile(session.id, session.sourceFiles.keySet().iterator().next(), session.sourceFiles.values().iterator().next().get(0).fileName);- fail("should have failed to obtain a file for an expired session");- } catch (SessionExpiredException e) {- // expected- }+ });}@Testdiff --git a/lucene/sandbox/src/test/org/apache/lucene/codecs/idversion/TestIDVersionPostingsFormat.java b/lucene/sandbox/src/test/org/apache/lucene/codecs/idversion/TestIDVersionPostingsFormat.javaindex efbd6ad4259..d173762a636 100644--- a/lucene/sandbox/src/test/org/apache/lucene/codecs/idversion/TestIDVersionPostingsFormat.java+++ b/lucene/sandbox/src/test/org/apache/lucene/codecs/idversion/TestIDVersionPostingsFormat.java@@ -363,15 +363,14 @@ public class TestIDVersionPostingsFormat extends LuceneTestCase {Document doc = new Document();doc.add(makeIDField("id", 17));w.addDocument(doc);- doc = new Document();- doc.add(makeIDField("id", 17));- try {- w.addDocument(doc);++ Document duplicate = new Document();+ duplicate.add(makeIDField("id", 17));+ expectThrows(IllegalArgumentException.class, () -> {+ w.addDocument(duplicate);w.commit();- fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w.close();dir.close();}@@ -464,13 +463,10 @@ public class TestIDVersionPostingsFormat extends LuceneTestCase {RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);Document doc = new Document();doc.add(newTextField("id", "id", Field.Store.NO));- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);w.commit();- fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });w.close();dir.close();@@ -483,13 +479,11 @@ public class TestIDVersionPostingsFormat extends LuceneTestCase {RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);Document doc = new Document();doc.add(newStringField("id", "id", Field.Store.NO));- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);w.commit();- fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w.close();dir.close();@@ -502,13 +496,10 @@ public class TestIDVersionPostingsFormat extends LuceneTestCase {RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);Document doc = new Document();doc.add(new StringAndPayloadField("id", "id", new BytesRef("foo")));- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);w.commit();- fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });w.close();dir.close();@@ -550,14 +541,12 @@ public class TestIDVersionPostingsFormat extends LuceneTestCase {ts.setValue("foo", payload);Field field = new Field("id", ts, ft);doc.add(new Field("id", ts, ft));- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);w.commit();fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- // iae.printStackTrace(System.out);- }+ });+w.close();dir.close();}@@ -570,13 +559,11 @@ public class TestIDVersionPostingsFormat extends LuceneTestCase {Document doc = new Document();doc.add(makeIDField("id", 17));doc.add(makeIDField("id", 17));- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);w.commit();- fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+w.close();dir.close();}@@ -589,19 +576,13 @@ public class TestIDVersionPostingsFormat extends LuceneTestCase {Document doc = new Document();// -1doc.add(new StringAndPayloadField("id", "id", new BytesRef(new byte[] {(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff})));- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);w.commit();- fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }- try {+ });+ expectThrows(AlreadyClosedException.class, () -> {w.addDocument(doc);- fail("should have hit exc");- } catch (AlreadyClosedException ace) {- // expected- }+ });dir.close();}@@ -613,19 +594,14 @@ public class TestIDVersionPostingsFormat extends LuceneTestCase {Document doc = new Document();// Long.MAX_VALUE:doc.add(new StringAndPayloadField("id", "id", new BytesRef(new byte[] {(byte)0x7f, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff})));- try {+ expectThrows(IllegalArgumentException.class, () -> {w.addDocument(doc);w.commit();- fail("didn't hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }- try {+ });+ expectThrows(AlreadyClosedException.class, () -> {w.addDocument(doc);- fail("should have hit exc");- } catch (AlreadyClosedException ace) {- // expected- }+ });+dir.close();}diff --git a/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSlowFuzzyQuery.java b/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSlowFuzzyQuery.javaindex 4b4aa38c2fe..922213fdc74 100644--- a/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSlowFuzzyQuery.java+++ b/lucene/sandbox/src/test/org/apache/lucene/sandbox/queries/TestSlowFuzzyQuery.java@@ -291,18 +291,13 @@ public class TestSlowFuzzyQuery extends LuceneTestCase {hits = searcher.search(query, 1000).scoreDocs;assertEquals(0, hits.length);- try {- query = new SlowFuzzyQuery(new Term("field", "student"), 1.1f);- fail("Expected IllegalArgumentException");- } catch (IllegalArgumentException e) {- // expecting exception- }- try {- query = new SlowFuzzyQuery(new Term("field", "student"), -0.1f);- fail("Expected IllegalArgumentException");- } catch (IllegalArgumentException e) {- // expecting exception- }+ expectThrows(IllegalArgumentException.class, () -> {+ new SlowFuzzyQuery(new Term("field", "student"), 1.1f);+ });++ expectThrows(IllegalArgumentException.class, () -> {+ new SlowFuzzyQuery(new Term("field", "student"), -0.1f);+ });reader.close();directory.close();diff --git a/lucene/sandbox/src/test/org/apache/lucene/search/TestTermAutomatonQuery.java b/lucene/sandbox/src/test/org/apache/lucene/search/TestTermAutomatonQuery.javaindex b5e784e5248..392941d513d 100644--- a/lucene/sandbox/src/test/org/apache/lucene/search/TestTermAutomatonQuery.java+++ b/lucene/sandbox/src/test/org/apache/lucene/search/TestTermAutomatonQuery.java@@ -357,12 +357,9 @@ public class TestTermAutomatonQuery extends LuceneTestCase {q.setAccept(s2, true);q.addAnyTransition(s0, s1);q.addTransition(s1, s2, "b");- try {+ expectThrows(IllegalStateException.class, () -> {q.finish();- fail("did not hit expected exception");- } catch (IllegalStateException ise) {- // expected- }+ });}public void testInvalidTrailWithAny() throws Exception {@@ -373,12 +370,9 @@ public class TestTermAutomatonQuery extends LuceneTestCase {q.setAccept(s2, true);q.addTransition(s0, s1, "b");q.addAnyTransition(s1, s2);- try {+ expectThrows(IllegalStateException.class, () -> {q.finish();- fail("did not hit expected exception");- } catch (IllegalStateException ise) {- // expected- }+ });}public void testAnyFromTokenStream() throws Exception {diff --git a/lucene/spatial/src/test/org/apache/lucene/spatial/geopoint/search/TestGeoPointQuery.java b/lucene/spatial/src/test/org/apache/lucene/spatial/geopoint/search/TestGeoPointQuery.javaindex bdc4d864011..13ce23520cd 100644--- a/lucene/spatial/src/test/org/apache/lucene/spatial/geopoint/search/TestGeoPointQuery.java+++ b/lucene/spatial/src/test/org/apache/lucene/spatial/geopoint/search/TestGeoPointQuery.java@@ -300,13 +300,11 @@ public class TestGeoPointQuery extends BaseGeoPointTestCase {assertEquals("smallTest failed", 2, td.totalHits);}+ // GeoBoundingBox should not accept invalid lat/lonpublic void testInvalidBBox() throws Exception {- try {+ expectThrows(Exception.class, () -> {bboxQuery(179.0, -92.0, 181.0, -91.0, 20);- } catch(Exception e) {- return;- }- throw new Exception("GeoBoundingBox should not accept invalid lat/lon");+ });}public void testGeoDistanceQuery() throws Exception {@@ -327,11 +325,10 @@ public class TestGeoPointQuery extends BaseGeoPointTestCase {}public void testTooBigRadius() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {geoDistanceQuery(0.0, 85.0, 4000000, 20);- } catch (IllegalArgumentException e) {- e.getMessage().contains("exceeds maxRadius");- }+ });+ assertTrue(expected.getMessage().contains("exceeds maxRadius"));}/**@@ -347,13 +344,11 @@ public class TestGeoPointQuery extends BaseGeoPointTestCase {assertEquals("GeoDistanceQuery failed", 3, td.totalHits);}+ // GeoDistanceQuery should not accept invalid lat/lon as originpublic void testInvalidGeoDistanceQuery() throws Exception {- try {+ expectThrows(Exception.class, () -> {geoDistanceQuery(181.0, 92.0, 120000, 20);- } catch (Exception e) {- return;- }- throw new Exception("GeoDistanceQuery should not accept invalid lat/lon as origin");+ });}public void testMaxDistanceRangeQuery() throws Exception {diff --git a/lucene/spatial/src/test/org/apache/lucene/spatial/query/SpatialArgsParserTest.java b/lucene/spatial/src/test/org/apache/lucene/spatial/query/SpatialArgsParserTest.javaindex b7bd50dc9ba..93b95f3d524 100644--- a/lucene/spatial/src/test/org/apache/lucene/spatial/query/SpatialArgsParserTest.java+++ b/lucene/spatial/src/test/org/apache/lucene/spatial/query/SpatialArgsParserTest.java@@ -47,19 +47,15 @@ public class SpatialArgsParserTest extends LuceneTestCase {out = parser.parse(arg, ctx);assertEquals(SpatialOperation.IsDisjointTo, out.getOperation());- try {+ // spatial operations need args+ expectThrows(Exception.class, () -> {parser.parse(SpatialOperation.IsDisjointTo + "[ ]", ctx);- fail("spatial operations need args");- }- catch (Exception ex) {//expected- }+ });- try {+ // unknown operation+ expectThrows(Exception.class, () -> {parser.parse("XXXX(Envelope(-10, 10, 20, -20))", ctx);- fail("unknown operation!");- }- catch (Exception ex) {//expected- }+ });assertAlias(SpatialOperation.IsWithin, "CoveredBy");assertAlias(SpatialOperation.IsWithin, "COVEREDBY");diff --git a/lucene/suggest/src/test/org/apache/lucene/search/spell/TestSpellChecker.java b/lucene/suggest/src/test/org/apache/lucene/search/spell/TestSpellChecker.javaindex 02484ad50c5..8428d8490d4 100644--- a/lucene/suggest/src/test/org/apache/lucene/search/spell/TestSpellChecker.java+++ b/lucene/suggest/src/test/org/apache/lucene/search/spell/TestSpellChecker.java@@ -310,12 +310,8 @@ public class TestSpellChecker extends LuceneTestCase {assertEquals(2, similar.length);assertEquals(similar[0], "ninety");assertEquals(similar[1], "one");- try {- similar = spellChecker.suggestSimilar("tousand", 10, r, null,- SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX);- } catch (NullPointerException e) {- assertTrue("threw an NPE, and it shouldn't have", false);- }+ // should not throw exception+ spellChecker.suggestSimilar("tousand", 10, r, null, SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX);}private void checkJaroWinklerSuggestions() throws IOException {@@ -361,39 +357,27 @@ public class TestSpellChecker extends LuceneTestCase {assertLastSearcherOpen(4);spellChecker.close();assertSearchersClosed();- try {++ expectThrows(AlreadyClosedException.class, () -> {spellChecker.close();- fail("spellchecker was already closed");- } catch (AlreadyClosedException e) {- // expected- }- try {+ });++ expectThrows(AlreadyClosedException.class, () -> {checkCommonSuggestions(r);- fail("spellchecker was already closed");- } catch (AlreadyClosedException e) {- // expected- }+ });- try {+ expectThrows(AlreadyClosedException.class, () -> {spellChecker.clearIndex();- fail("spellchecker was already closed");- } catch (AlreadyClosedException e) {- // expected- }+ });- try {+ expectThrows(AlreadyClosedException.class, () -> {spellChecker.indexDictionary(new LuceneDictionary(r, field), newIndexWriterConfig(null), false);- fail("spellchecker was already closed");- } catch (AlreadyClosedException e) {- // expected- }+ });- try {+ expectThrows(AlreadyClosedException.class, () -> {spellChecker.setSpellIndex(spellindex);- fail("spellchecker was already closed");- } catch (AlreadyClosedException e) {- // expected- }+ });+assertEquals(4, searchers.size());assertSearchersClosed();r.close();diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/AnalyzingInfixSuggesterTest.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/AnalyzingInfixSuggesterTest.javaindex 092eb959d62..44ecf8881bc 100644--- a/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/AnalyzingInfixSuggesterTest.java+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/AnalyzingInfixSuggesterTest.java@@ -41,6 +41,7 @@ import org.apache.lucene.search.BooleanQuery;import org.apache.lucene.search.suggest.Input;import org.apache.lucene.search.suggest.InputArrayIterator;import org.apache.lucene.search.suggest.Lookup.LookupResult;+import org.apache.lucene.store.AlreadyClosedException;import org.apache.lucene.store.Directory;import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.IOUtils;@@ -877,12 +878,11 @@ public class AnalyzingInfixSuggesterTest extends LuceneTestCase {Path tempDir = createTempDir("AIS_NRT_PERSIST_TEST");AnalyzingInfixSuggester suggester = new AnalyzingInfixSuggester(newFSDirectory(tempDir), a, a, 3, false);Thread[] multiAddThreads = new Thread[10];- try {+ // Cannot call refresh on an suggester when no docs are added to the index+ expectThrows(IllegalStateException.class, () -> {suggester.refresh();- fail("Cannot call refresh on an suggester when no docs are added to the index");- } catch(IllegalStateException e) {- //Expected- }+ });+for(int i=0; i<10; i++) {multiAddThreads[i] = new Thread(new IndexDocument(suggester, keys[i]));}@@ -903,12 +903,12 @@ public class AnalyzingInfixSuggesterTest extends LuceneTestCase {suggester.commit();suggester.close();- suggester = new AnalyzingInfixSuggester(newFSDirectory(tempDir), a, a, 3, false);- results = suggester.lookup(TestUtil.stringToCharSequence("python", random()), 10, true, false);+ AnalyzingInfixSuggester suggester2 = new AnalyzingInfixSuggester(newFSDirectory(tempDir), a, a, 3, false);+ results = suggester2.lookup(TestUtil.stringToCharSequence("python", random()), 10, true, false);assertEquals(1, results.size());assertEquals("python", results.get(0).key);- suggester.close();+ suggester2.close();a.close();}diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/AnalyzingSuggesterTest.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/AnalyzingSuggesterTest.javaindex 8890a8280de..7baa73c0f91 100644--- a/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/AnalyzingSuggesterTest.java+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/AnalyzingSuggesterTest.java@@ -1224,18 +1224,13 @@ public class AnalyzingSuggesterTest extends LuceneTestCase {suggester.build(new InputArrayIterator(new Input[] {new Input("а где Люси?", 7),}));- try {+ expectThrows(IllegalArgumentException.class, () -> {suggester.lookup("а\u001E", false, 3);- fail("should throw IllegalArgumentException");- } catch (IllegalArgumentException e) {- // expected- }- try {+ });+ expectThrows(IllegalArgumentException.class, () -> {suggester.lookup("а\u001F", false, 3);- fail("should throw IllegalArgumentException");- } catch (IllegalArgumentException e) {- // expected- }+ });+IOUtils.close(a, tempDir);}diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/TestFreeTextSuggester.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/TestFreeTextSuggester.javaindex 45a68551583..4fd7773f1d6 100644--- a/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/TestFreeTextSuggester.java+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/TestFreeTextSuggester.java@@ -105,12 +105,10 @@ public class TestFreeTextSuggester extends LuceneTestCase {);Analyzer analyzer = new MockAnalyzer(random());FreeTextSuggester sug = new FreeTextSuggester(analyzer);- try {+ expectThrows(IllegalArgumentException.class, () -> {sug.build(new InputArrayIterator(keys));- fail("did not hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+analyzer.close();}@@ -124,12 +122,10 @@ public class TestFreeTextSuggester extends LuceneTestCase {FreeTextSuggester sug = new FreeTextSuggester(analyzer);sug.build(new InputArrayIterator(keys));- try {+ expectThrows(IllegalArgumentException.class, () -> {sug.lookup("foo\u001eb", 10);- fail("did not hit expected exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+analyzer.close();}@@ -234,12 +230,10 @@ public class TestFreeTextSuggester extends LuceneTestCase {Analyzer a = new MockAnalyzer(random());FreeTextSuggester sug = new FreeTextSuggester(a, a, 2, (byte) 0x20);sug.build(new InputArrayIterator(keys));- try {+ expectThrows(IllegalArgumentException.class, () -> {sug.lookup("", 10);- fail("did not hit exception");- } catch (IllegalArgumentException iae) {- // expected- }+ });+a.close();}diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/TestSuggestStopFilterFactory.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/TestSuggestStopFilterFactory.javaindex b901c21edc3..58b18925df3 100644--- a/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/TestSuggestStopFilterFactory.java+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/TestSuggestStopFilterFactory.java@@ -69,37 +69,33 @@ public class TestSuggestStopFilterFactory extends BaseTokenStreamTestCase {/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {createFactory("bogusArg", "bogusValue");- fail();- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("Unknown parameters"));- }+ });+ assertTrue(expected.getMessage().contains("Unknown parameters"));}/** Test that bogus arguments result in exception */public void testBogusFormats() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {createFactory("words", "stop-snowball.txt","format", "bogus");- fail();- } catch (IllegalArgumentException expected) {- String msg = expected.getMessage();- assertTrue(msg, msg.contains("Unknown"));- assertTrue(msg, msg.contains("format"));- assertTrue(msg, msg.contains("bogus"));- }- try {+ });++ String msg = expected.getMessage();+ assertTrue(msg, msg.contains("Unknown"));+ assertTrue(msg, msg.contains("format"));+ assertTrue(msg, msg.contains("bogus"));++ expected = expectThrows(IllegalArgumentException.class, () -> {createFactory(// implicit default words file"format", "bogus");- fail();- } catch (IllegalArgumentException expected) {- String msg = expected.getMessage();- assertTrue(msg, msg.contains("can not be specified"));- assertTrue(msg, msg.contains("format"));- assertTrue(msg, msg.contains("bogus"));- }+ });+ msg = expected.getMessage();+ assertTrue(msg, msg.contains("can not be specified"));+ assertTrue(msg, msg.contains("format"));+ assertTrue(msg, msg.contains("bogus"));}private SuggestStopFilterFactory createFactory(String ... params) throws IOException {diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestContextQuery.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestContextQuery.javaindex 1be3f37d6cb..35661ee7480 100644--- a/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestContextQuery.java+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestContextQuery.java@@ -56,13 +56,11 @@ public class TestContextQuery extends LuceneTestCase {@Testpublic void testIllegalInnerQuery() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new ContextQuery(new ContextQuery(new PrefixCompletionQuery(new MockAnalyzer(random()), new Term("suggest_field", "sugg"))));- fail("should error out trying to nest a Context query within another Context query");- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains(ContextQuery.class.getSimpleName()));- }+ });+ assertTrue(expected.getMessage().contains(ContextQuery.class.getSimpleName()));}@Test@@ -125,11 +123,11 @@ public class TestContextQuery extends LuceneTestCase {DirectoryReader reader = iw.getReader();SuggestIndexSearcher suggestIndexSearcher = new SuggestIndexSearcher(reader);ContextQuery query = new ContextQuery(new PrefixCompletionQuery(analyzer, new Term("suggest_field", "ab")));- try {+ IllegalStateException expected = expectThrows(IllegalStateException.class, () -> {suggestIndexSearcher.suggest(query, 4);- } catch (IllegalStateException expected) {- assertTrue(expected.getMessage().contains("SuggestField"));- }+ });+ assertTrue(expected.getMessage().contains("SuggestField"));+reader.close();iw.close();}diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestContextSuggestField.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestContextSuggestField.javaindex 4f236798082..9f207f80ef2 100644--- a/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestContextSuggestField.java+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestContextSuggestField.java@@ -56,12 +56,10 @@ public class TestContextSuggestField extends LuceneTestCase {@Testpublic void testEmptySuggestion() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new ContextSuggestField("suggest_field", "", 1, "type1");- fail("no exception thrown when indexing zero length suggestion");- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("value"));- }+ });+ assertTrue(expected.getMessage().contains("value"));}@Test@@ -73,22 +71,24 @@ public class TestContextSuggestField extends LuceneTestCase {Analyzer analyzer = new MockAnalyzer(random());Document document = new Document();try (RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "name"))) {- document.add(new ContextSuggestField("name", "sugg", 1, charsRefBuilder.toString()));- iw.addDocument(document);- iw.commit();- fail("no exception thrown for context value containing CONTEXT_SEPARATOR:" + ContextSuggestField.CONTEXT_SEPARATOR);- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("[0x1d]"));+ // exception should be thrown for context value containing CONTEXT_SEPARATOR+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ document.add(new ContextSuggestField("name", "sugg", 1, charsRefBuilder.toString()));+ iw.addDocument(document);+ iw.commit();+ });+ assertTrue(expected.getMessage().contains("[0x1d]"));}document.clear();try (RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwcWithSuggestField(analyzer, "name"))) {- document.add(new ContextSuggestField("name", charsRefBuilder.toString(), 1, "sugg"));- iw.addDocument(document);- iw.commit();- fail("no exception thrown for value containing CONTEXT_SEPARATOR:" + ContextSuggestField.CONTEXT_SEPARATOR);- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("[0x1d]"));+ // exception should be thrown for context value containing CONTEXT_SEPARATOR+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ document.add(new ContextSuggestField("name", charsRefBuilder.toString(), 1, "sugg"));+ iw.addDocument(document);+ iw.commit();+ });+ assertTrue(expected.getMessage().contains("[0x1d]"));}}@@ -135,10 +135,11 @@ public class TestContextSuggestField extends LuceneTestCase {try (RandomIndexWriter iw = new RandomIndexWriter(random(), dir,iwcWithSuggestField(analyzer, "suggest_field"))) {- iw.addDocument(document);- iw.commit();- fail("mixing suggest field types for same field name should error out");- } catch (IllegalArgumentException expected) {+ // mixing suggest field types for same field name should error out+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {+ iw.addDocument(document);+ iw.commit();+ });assertTrue(expected.getMessage().contains("mixed types"));}}diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestSuggestField.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestSuggestField.javaindex 1e2b946f93f..3d2759dac9b 100644--- a/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestSuggestField.java+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestSuggestField.java@@ -79,22 +79,18 @@ public class TestSuggestField extends LuceneTestCase {@Testpublic void testEmptySuggestion() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new SuggestField("suggest_field", "", 3);- fail("no exception thrown when indexing zero length suggestion");- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("value"));- }+ });+ assertTrue(expected.getMessage().contains("value"));}@Testpublic void testNegativeWeight() throws Exception {- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new SuggestField("suggest_field", "sugg", -1);- fail("no exception thrown when indexing suggestion with negative weight");- } catch (IllegalArgumentException expected) {- assertTrue(expected.getMessage().contains("weight"));- }+ });+ assertTrue(expected.getMessage().contains("weight"));}@Test@@ -102,28 +98,22 @@ public class TestSuggestField extends LuceneTestCase {CharsRefBuilder charsRefBuilder = new CharsRefBuilder();charsRefBuilder.append("sugg");charsRefBuilder.setCharAt(2, (char) CompletionAnalyzer.SEP_LABEL);- try {+ IllegalArgumentException expected = expectThrows(IllegalArgumentException.class, () -> {new SuggestField("name", charsRefBuilder.toString(), 1);- fail("no exception thrown for suggestion value containing SEP_LABEL:" + CompletionAnalyzer.SEP_LABEL);- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("[0x1f]"));- }+ });+ assertTrue(expected.getMessage().contains("[0x1f]"));charsRefBuilder.setCharAt(2, (char) CompletionAnalyzer.HOLE_CHARACTER);- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {new SuggestField("name", charsRefBuilder.toString(), 1);- fail("no exception thrown for suggestion value containing HOLE_CHARACTER:" + CompletionAnalyzer.HOLE_CHARACTER);- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("[0x1e]"));- }+ });+ assertTrue(expected.getMessage().contains("[0x1e]"));charsRefBuilder.setCharAt(2, (char) NRTSuggesterBuilder.END_BYTE);- try {+ expected = expectThrows(IllegalArgumentException.class, () -> {new SuggestField("name", charsRefBuilder.toString(), 1);- fail("no exception thrown for suggestion value containing END_BYTE:" + NRTSuggesterBuilder.END_BYTE);- } catch (IllegalArgumentException e) {- assertTrue(e.getMessage().contains("[0x0]"));- }+ });+ assertTrue(expected.getMessage().contains("[0x0]"));}@Testdiff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/fst/BytesRefSortersTest.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/fst/BytesRefSortersTest.javaindex 4f4a126950e..1006700d89f 100644--- a/lucene/suggest/src/test/org/apache/lucene/search/suggest/fst/BytesRefSortersTest.java+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/fst/BytesRefSortersTest.java@@ -52,12 +52,10 @@ public class BytesRefSortersTest extends LuceneTestCase {BytesRefIterator i2 = sorter.iterator();// Verify sorter contract.- try {+ expectThrows(IllegalStateException.class, () -> {sorter.add(new BytesRef(new byte [1]));- fail("expected contract violation.");- } catch (IllegalStateException e) {- // Expected.- }+ });+BytesRef spare1;BytesRef spare2;while ((spare1 = i1.next()) != null && (spare2 = i2.next()) != null) {diff --git a/lucene/test-framework/src/java/org/apache/lucene/index/BaseCompoundFormatTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/index/BaseCompoundFormatTestCase.javaindex 877d74a1811..f09be9d05a6 100644--- a/lucene/test-framework/src/java/org/apache/lucene/index/BaseCompoundFormatTestCase.java+++ b/lucene/test-framework/src/java/org/apache/lucene/index/BaseCompoundFormatTestCase.java@@ -222,12 +222,10 @@ public abstract class BaseCompoundFormatTestCase extends BaseIndexFileFormatTestsi.setFiles(Collections.emptyList());si.getCodec().compoundFormat().write(dir, si, IOContext.DEFAULT);Directory cfs = si.getCodec().compoundFormat().getCompoundReader(dir, si, IOContext.DEFAULT);- try {+ expectThrows(UnsupportedOperationException.class, () -> {cfs.createOutput("bogus", IOContext.DEFAULT);- fail("didn't get expected exception");- } catch (UnsupportedOperationException expected) {- // expected UOE- }+ });+cfs.close();dir.close();}@@ -245,12 +243,10 @@ public abstract class BaseCompoundFormatTestCase extends BaseIndexFileFormatTestsi.setFiles(Collections.emptyList());si.getCodec().compoundFormat().write(dir, si, IOContext.DEFAULT);Directory cfs = si.getCodec().compoundFormat().getCompoundReader(dir, si, IOContext.DEFAULT);- try {+ expectThrows(UnsupportedOperationException.class, () -> {cfs.deleteFile(testfile);- fail("didn't get expected exception");- } catch (UnsupportedOperationException expected) {- // expected UOE- }+ });+cfs.close();dir.close();}@@ -268,12 +264,10 @@ public abstract class BaseCompoundFormatTestCase extends BaseIndexFileFormatTestsi.setFiles(Collections.emptyList());si.getCodec().compoundFormat().write(dir, si, IOContext.DEFAULT);Directory cfs = si.getCodec().compoundFormat().getCompoundReader(dir, si, IOContext.DEFAULT);- try {+ expectThrows(UnsupportedOperationException.class, () -> {cfs.renameFile(testfile, "bogus");- fail("didn't get expected exception");- } catch (UnsupportedOperationException expected) {- // expected UOE- }+ });+cfs.close();dir.close();}@@ -291,12 +285,10 @@ public abstract class BaseCompoundFormatTestCase extends BaseIndexFileFormatTestsi.setFiles(Collections.emptyList());si.getCodec().compoundFormat().write(dir, si, IOContext.DEFAULT);Directory cfs = si.getCodec().compoundFormat().getCompoundReader(dir, si, IOContext.DEFAULT);- try {+ expectThrows(UnsupportedOperationException.class, () -> {cfs.sync(Collections.singleton(testfile));- fail("didn't get expected exception");- } catch (UnsupportedOperationException expected) {- // expected UOE- }+ });+cfs.close();dir.close();}@@ -314,12 +306,10 @@ public abstract class BaseCompoundFormatTestCase extends BaseIndexFileFormatTestsi.setFiles(Collections.emptyList());si.getCodec().compoundFormat().write(dir, si, IOContext.DEFAULT);Directory cfs = si.getCodec().compoundFormat().getCompoundReader(dir, si, IOContext.DEFAULT);- try {+ expectThrows(UnsupportedOperationException.class, () -> {cfs.obtainLock("foobar");- fail("didn't get expected exception");- } catch (UnsupportedOperationException expected) {- // expected UOE- }+ });+cfs.close();dir.close();}@@ -602,12 +592,9 @@ public abstract class BaseCompoundFormatTestCase extends BaseIndexFileFormatTestDirectory cr = createLargeCFS(dir);// Open bogus file- try {+ expectThrows(IOException.class, () -> {cr.openInput("bogus", newIOContext(random()));- fail("File not found");- } catch (IOException e) {- /* success */;- }+ });cr.close();dir.close();@@ -620,21 +607,18 @@ public abstract class BaseCompoundFormatTestCase extends BaseIndexFileFormatTestis.seek(is.length() - 10);byte b[] = new byte[100];is.readBytes(b, 0, 10);-- try {++ // Single byte read past end of file+ expectThrows(IOException.class, () -> {is.readByte();- fail("Single byte read past end of file");- } catch (IOException e) {- /* success */- }-+ });+is.seek(is.length() - 10);- try {++ // Block read past end of file+ expectThrows(IOException.class, () -> {is.readBytes(b, 0, 50);- fail("Block read past end of file");- } catch (IOException e) {- /* success */- }+ });is.close();cr.close();diff --git a/lucene/test-framework/src/java/org/apache/lucene/index/BaseFieldInfoFormatTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/index/BaseFieldInfoFormatTestCase.javaindex d81f18894c5..d8e2296e336 100644--- a/lucene/test-framework/src/java/org/apache/lucene/index/BaseFieldInfoFormatTestCase.java+++ b/lucene/test-framework/src/java/org/apache/lucene/index/BaseFieldInfoFormatTestCase.java@@ -87,12 +87,11 @@ public abstract class BaseFieldInfoFormatTestCase extends BaseIndexFileFormatTesassertEquals(1, infos2.size());assertNotNull(infos2.fieldInfo("field"));Map<String,String> attributes = infos2.fieldInfo("field").attributes();- try {+ // shouldn't be able to modify attributes+ expectThrows(UnsupportedOperationException.class, () -> {attributes.put("bogus", "bogus");- fail("shouldn't be able to modify attributes");- } catch (UnsupportedOperationException expected) {- // ok- }+ });+dir.close();}@@ -123,14 +122,10 @@ public abstract class BaseFieldInfoFormatTestCase extends BaseIndexFileFormatTesFieldInfos infos = builder.finish();fail.setDoFail();- try {+ expectThrows(FakeIOException.class, () -> {codec.fieldInfosFormat().write(dir, segmentInfo, "", infos, IOContext.DEFAULT);- fail("didn't get expected exception");- } catch (FakeIOException expected) {- // ok- } finally {- fail.clearDoFail();- }+ });+ fail.clearDoFail();dir.close();}@@ -162,14 +157,10 @@ public abstract class BaseFieldInfoFormatTestCase extends BaseIndexFileFormatTesFieldInfos infos = builder.finish();fail.setDoFail();- try {+ expectThrows(FakeIOException.class, () -> {codec.fieldInfosFormat().write(dir, segmentInfo, "", infos, IOContext.DEFAULT);- fail("didn't get expected exception");- } catch (FakeIOException expected) {- // ok- } finally {- fail.clearDoFail();- }+ });+ fail.clearDoFail();dir.close();}@@ -202,14 +193,10 @@ public abstract class BaseFieldInfoFormatTestCase extends BaseIndexFileFormatTescodec.fieldInfosFormat().write(dir, segmentInfo, "", infos, IOContext.DEFAULT);fail.setDoFail();- try {- codec.fieldInfosFormat().read(dir, segmentInfo, "", IOContext.DEFAULT);- fail("didn't get expected exception");- } catch (FakeIOException expected) {- // ok- } finally {- fail.clearDoFail();- }+ expectThrows(FakeIOException.class, () -> {+ codec.fieldInfosFormat().read(dir, segmentInfo, "", IOContext.DEFAULT);+ });+ fail.clearDoFail();dir.close();}@@ -242,14 +229,10 @@ public abstract class BaseFieldInfoFormatTestCase extends BaseIndexFileFormatTescodec.fieldInfosFormat().write(dir, segmentInfo, "", infos, IOContext.DEFAULT);fail.setDoFail();- try {- codec.fieldInfosFormat().read(dir, segmentInfo, "", IOContext.DEFAULT);- fail("didn't get expected exception");- } catch (FakeIOException expected) {- // ok- } finally {- fail.clearDoFail();- }+ expectThrows(FakeIOException.class, () -> {+ codec.fieldInfosFormat().read(dir, segmentInfo, "", IOContext.DEFAULT);+ });+ fail.clearDoFail();dir.close();}diff --git a/lucene/test-framework/src/java/org/apache/lucene/index/BaseSegmentInfoFormatTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/index/BaseSegmentInfoFormatTestCase.javaindex 3a4ebf7db03..1136afa64fb 100644--- a/lucene/test-framework/src/java/org/apache/lucene/index/BaseSegmentInfoFormatTestCase.java+++ b/lucene/test-framework/src/java/org/apache/lucene/index/BaseSegmentInfoFormatTestCase.java@@ -77,12 +77,12 @@ public abstract class BaseSegmentInfoFormatTestCase extends BaseIndexFileFormatTSegmentInfo info2 = codec.segmentInfoFormat().read(dir, "_123", id, IOContext.DEFAULT);assertEquals(info.files(), info2.files());- try {++ // files set should be immutable+ expectThrows(UnsupportedOperationException.class, () -> {info2.files().add("bogus");- fail("files set should be immutable");- } catch (UnsupportedOperationException expected) {- // ok- }+ });+dir.close();}@@ -100,12 +100,12 @@ public abstract class BaseSegmentInfoFormatTestCase extends BaseIndexFileFormatTcodec.segmentInfoFormat().write(dir, info, IOContext.DEFAULT);SegmentInfo info2 = codec.segmentInfoFormat().read(dir, "_123", id, IOContext.DEFAULT);assertEquals(diagnostics, info2.getDiagnostics());- try {++ // diagnostics map should be immutable+ expectThrows(UnsupportedOperationException.class, () -> {info2.getDiagnostics().put("bogus", "bogus");- fail("diagnostics map should be immutable");- } catch (UnsupportedOperationException expected) {- // ok- }+ });+dir.close();}@@ -123,12 +123,12 @@ public abstract class BaseSegmentInfoFormatTestCase extends BaseIndexFileFormatTcodec.segmentInfoFormat().write(dir, info, IOContext.DEFAULT);SegmentInfo info2 = codec.segmentInfoFormat().read(dir, "_123", id, IOContext.DEFAULT);assertEquals(attributes, info2.getAttributes());- try {++ // attributes map should be immutable+ expectThrows(UnsupportedOperationException.class, () -> {info2.getAttributes().put("bogus", "bogus");- fail("attributes map should be immutable");- } catch (UnsupportedOperationException expected) {- // ok- }+ });+dir.close();}@@ -187,14 +187,10 @@ public abstract class BaseSegmentInfoFormatTestCase extends BaseIndexFileFormatTinfo.setFiles(Collections.<String>emptySet());fail.setDoFail();- try {+ expectThrows(FakeIOException.class, () -> {codec.segmentInfoFormat().write(dir, info, IOContext.DEFAULT);- fail("didn't get expected exception");- } catch (FakeIOException expected) {- // ok- } finally {- fail.clearDoFail();- }+ });+ fail.clearDoFail();dir.close();}@@ -224,14 +220,10 @@ public abstract class BaseSegmentInfoFormatTestCase extends BaseIndexFileFormatTinfo.setFiles(Collections.<String>emptySet());fail.setDoFail();- try {+ expectThrows(FakeIOException.class, () -> {codec.segmentInfoFormat().write(dir, info, IOContext.DEFAULT);- fail("didn't get expected exception");- } catch (FakeIOException expected) {- // ok- } finally {- fail.clearDoFail();- }+ });+ fail.clearDoFail();dir.close();}@@ -262,14 +254,10 @@ public abstract class BaseSegmentInfoFormatTestCase extends BaseIndexFileFormatTcodec.segmentInfoFormat().write(dir, info, IOContext.DEFAULT);fail.setDoFail();- try {+ expectThrows(FakeIOException.class, () -> {codec.segmentInfoFormat().read(dir, "_123", id, IOContext.DEFAULT);- fail("didn't get expected exception");- } catch (FakeIOException expected) {- // ok- } finally {- fail.clearDoFail();- }+ });+ fail.clearDoFail();dir.close();}@@ -300,14 +288,11 @@ public abstract class BaseSegmentInfoFormatTestCase extends BaseIndexFileFormatTcodec.segmentInfoFormat().write(dir, info, IOContext.DEFAULT);fail.setDoFail();- try {+ expectThrows(FakeIOException.class, () -> {codec.segmentInfoFormat().read(dir, "_123", id, IOContext.DEFAULT);- fail("didn't get expected exception");- } catch (FakeIOException expected) {- // ok- } finally {- fail.clearDoFail();- }+ });+ fail.clearDoFail();+dir.close();}diff --git a/lucene/test-framework/src/java/org/apache/lucene/index/BaseTestCheckIndex.java b/lucene/test-framework/src/java/org/apache/lucene/index/BaseTestCheckIndex.javaindex f39645785e8..cdec720f134 100644--- a/lucene/test-framework/src/java/org/apache/lucene/index/BaseTestCheckIndex.java+++ b/lucene/test-framework/src/java/org/apache/lucene/index/BaseTestCheckIndex.java@@ -172,13 +172,10 @@ public class BaseTestCheckIndex extends LuceneTestCase {iw.addDocument(new Document());iw.commit();- // keep IW open...- try {+ // keep IW open... should not be able to obtain write lock+ expectThrows(LockObtainFailedException.class, () -> {new CheckIndex(dir);- fail("should not have obtained write lock");- } catch (LockObtainFailedException expected) {- // ok- }+ });iw.close();}diff --git a/lucene/test-framework/src/java/org/apache/lucene/index/DocHelper.java b/lucene/test-framework/src/java/org/apache/lucene/index/DocHelper.javaindex 240f4454a67..cac861ea3ba 100644--- a/lucene/test-framework/src/java/org/apache/lucene/index/DocHelper.java+++ b/lucene/test-framework/src/java/org/apache/lucene/index/DocHelper.java@@ -18,6 +18,7 @@ package org.apache.lucene.index;import java.io.IOException;import java.io.UnsupportedEncodingException;+import java.nio.charset.StandardCharsets;import java.util.HashMap;import java.util.Map;import java.util.Random;@@ -190,10 +191,7 @@ class DocHelper {buffer.append("Lazily loading lengths of language in lieu of laughing ");}- try {- LAZY_FIELD_BINARY_BYTES = "These are some binary field bytes".getBytes("UTF8");- } catch (UnsupportedEncodingException e) {- }+ LAZY_FIELD_BINARY_BYTES = "These are some binary field bytes".getBytes(StandardCharsets.UTF_8);lazyFieldBinary = new StoredField(LAZY_FIELD_BINARY_KEY, LAZY_FIELD_BINARY_BYTES);fields[fields.length - 2] = lazyFieldBinary;LARGE_LAZY_FIELD_TEXT = buffer.toString();diff --git a/lucene/test-framework/src/java/org/apache/lucene/index/RandomPostingsTester.java b/lucene/test-framework/src/java/org/apache/lucene/index/RandomPostingsTester.javaindex 973fa5e7e52..90064c4d7ff 100644--- a/lucene/test-framework/src/java/org/apache/lucene/index/RandomPostingsTester.java+++ b/lucene/test-framework/src/java/org/apache/lucene/index/RandomPostingsTester.java@@ -1239,12 +1239,9 @@ public class RandomPostingsTester {}}assertFalse(iterator.hasNext());- try {+ LuceneTestCase.expectThrows(NoSuchElementException.class, () -> {iterator.next();- throw new AssertionError("Fields.iterator() doesn't throw NoSuchElementException when past the end");- } catch (NoSuchElementException expected) {- // expected- }+ });}/** Indexes all fields/terms at the specifieddiff --git a/lucene/test-framework/src/java/org/apache/lucene/store/BaseDirectoryTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/store/BaseDirectoryTestCase.javaindex 3d9c20dd46f..5f66074718e 100644--- a/lucene/test-framework/src/java/org/apache/lucene/store/BaseDirectoryTestCase.java+++ b/lucene/test-framework/src/java/org/apache/lucene/store/BaseDirectoryTestCase.java@@ -365,32 +365,26 @@ public abstract class BaseDirectoryTestCase extends LuceneTestCase {output.close();IndexInput input = dir.openInput("stringset", newIOContext(random()));- Set<String> set = input.readSetOfStrings();- assertEquals(asSet("test1", "test2"), set);- try {- set.add("bogus");- fail("set should be immutable");- } catch (UnsupportedOperationException expected) {- // ok- }-- set = input.readSetOfStrings();- assertEquals(Collections.emptySet(), set);- try {- set.add("bogus");- fail("set should be immutable");- } catch (UnsupportedOperationException expected) {- // ok- }-- set = input.readSetOfStrings();- assertEquals(Collections.singleton("test3"), set);- try {- set.add("bogus");- fail("set should be immutable");- } catch (UnsupportedOperationException expected) {- // ok- }+ Set<String> set1 = input.readSetOfStrings();+ assertEquals(asSet("test1", "test2"), set1);+ // set should be immutable+ expectThrows(UnsupportedOperationException.class, () -> {+ set1.add("bogus");+ });++ Set<String> set2 = input.readSetOfStrings();+ assertEquals(Collections.emptySet(), set2);+ // set should be immutable+ expectThrows(UnsupportedOperationException.class, () -> {+ set2.add("bogus");+ });++ Set<String> set3 = input.readSetOfStrings();+ assertEquals(Collections.singleton("test3"), set3);+ // set should be immutable+ expectThrows(UnsupportedOperationException.class, () -> {+ set3.add("bogus");+ });assertEquals(input.length(), input.getFilePointer());input.close();@@ -410,32 +404,26 @@ public abstract class BaseDirectoryTestCase extends LuceneTestCase {output.close();IndexInput input = dir.openInput("stringmap", newIOContext(random()));- Map<String,String> map = input.readMapOfStrings();- assertEquals(m, map);- try {- map.put("bogus1", "bogus2");- fail("map should be immutable");- } catch (UnsupportedOperationException expected) {- // ok- }-- map = input.readMapOfStrings();- assertEquals(Collections.emptyMap(), map);- try {- map.put("bogus1", "bogus2");- fail("map should be immutable");- } catch (UnsupportedOperationException expected) {- // ok- }-- map = input.readMapOfStrings();- assertEquals(Collections.singletonMap("key", "value"), map);- try {- map.put("bogus1", "bogus2");- fail("map should be immutable");- } catch (UnsupportedOperationException expected) {- // ok- }+ Map<String,String> map1 = input.readMapOfStrings();+ assertEquals(m, map1);+ // map should be immutable+ expectThrows(UnsupportedOperationException.class, () -> {+ map1.put("bogus1", "bogus2");+ });++ Map<String,String> map2 = input.readMapOfStrings();+ assertEquals(Collections.emptyMap(), map2);+ // map should be immutable+ expectThrows(UnsupportedOperationException.class, () -> {+ map2.put("bogus1", "bogus2");+ });++ Map<String,String> map3 = input.readMapOfStrings();+ assertEquals(Collections.singletonMap("key", "value"), map3);+ // map should be immutable+ expectThrows(UnsupportedOperationException.class, () -> {+ map3.put("bogus1", "bogus2");+ });assertEquals(input.length(), input.getFilePointer());input.close();@@ -468,12 +456,9 @@ public abstract class BaseDirectoryTestCase extends LuceneTestCase {public void testDetectClose() throws Throwable {Directory dir = getDirectory(createTempDir("testDetectClose"));dir.close();- try {+ expectThrows(AlreadyClosedException.class, () -> {dir.createOutput("test", newIOContext(random()));- fail("did not hit expected exception");- } catch (AlreadyClosedException ace) {- // expected- }+ });}public void testThreadSafety() throws Exception {@@ -622,13 +607,11 @@ public abstract class BaseDirectoryTestCase extends LuceneTestCase {o.writeBytes(b, 0, len);o.close();IndexInput i = dir.openInput("out", newIOContext(random()));- try {+ expectThrows(EOFException.class, () -> {i.seek(len + random().nextInt(2048));i.readByte();- fail("Did not get EOFException");- } catch (EOFException eof) {- // pass- }+ });+i.close();dir.close();}@@ -641,25 +624,19 @@ public abstract class BaseDirectoryTestCase extends LuceneTestCase {o.writeBytes(b, 0, len);o.close();IndexInput i = dir.openInput("out", newIOContext(random()));- try {+ expectThrows(IllegalArgumentException.class, () -> {i.slice("slice1", 0, len + 1);- fail("Did not get IllegalArgumentException");- } catch (IllegalArgumentException iae) {- // pass- }- try {+ });++ expectThrows(IllegalArgumentException.class, () -> {i.slice("slice2", -1, len);- fail("Did not get IllegalArgumentException");- } catch (IllegalArgumentException iae) {- // pass- }+ });+IndexInput slice = i.slice("slice3", 4, len / 2);- try {+ expectThrows(IllegalArgumentException.class, () -> {slice.slice("slice3sub", 1, len / 2);- fail("Did not get IllegalArgumentException");- } catch (IllegalArgumentException iae) {- // pass- }+ });+i.close();dir.close();}@@ -1215,12 +1192,9 @@ public abstract class BaseDirectoryTestCase extends LuceneTestCase {try (IndexInput in = dir.openInput("a", IOContext.DEFAULT)) {in.seek(100);assertEquals(100, in.getFilePointer());- try {+ expectThrows(EOFException.class, () -> {in.seek(1025);- fail("didn't hit expected exception");- } catch (EOFException eofe) {- // expected- }+ });}}}@@ -1232,17 +1206,18 @@ public abstract class BaseDirectoryTestCase extends LuceneTestCase {FSDirectory fsDir = (FSDirectory) dir;// Keep trying until virus checker refuses to delete:- String fileName;+ final String fileName;while (true) {- fileName = TestUtil.randomSimpleString(random());- if (fileName.length() == 0) {+ String candidate = TestUtil.randomSimpleString(random());+ if (candidate.length() == 0) {continue;}- try (IndexOutput out = dir.createOutput(fileName, IOContext.DEFAULT)) {+ try (IndexOutput out = dir.createOutput(candidate, IOContext.DEFAULT)) {}- fsDir.deleteFile(fileName);+ fsDir.deleteFile(candidate);if (fsDir.checkPendingDeletions()) {// good: virus checker struck and prevented deletion of fileName+ fileName = candidate;break;}}@@ -1251,35 +1226,23 @@ public abstract class BaseDirectoryTestCase extends LuceneTestCase {assertFalse(Arrays.asList(fsDir.listAll()).contains(fileName));// Make sure fileLength claims it's deleted:- try {+ expectThrows(NoSuchFileException.class, () -> {fsDir.fileLength(fileName);- fail("did not hit exception");- } catch (NoSuchFileException nsfe) {- // expected- }+ });// Make sure rename fails:- try {+ expectThrows(NoSuchFileException.class, () -> {fsDir.renameFile(fileName, "file2");- fail("did not hit exception");- } catch (NoSuchFileException nsfe) {- // expected- }+ });// Make sure delete fails:- try {+ expectThrows(NoSuchFileException.class, () -> {fsDir.deleteFile(fileName);- fail("did not hit exception");- } catch (NoSuchFileException nsfe) {- // expected- }+ });- try {+ expectThrows(NoSuchFileException.class, () -> {fsDir.openInput(fileName, IOContext.DEFAULT);- fail("did not hit exception");- } catch (NoSuchFileException nsfe) {- // expected- }+ });if (random().nextBoolean()) {try (IndexOutput out = fsDir.createOutput(fileName + "z", IOContext.DEFAULT)) {diff --git a/lucene/test-framework/src/java/org/apache/lucene/store/BaseLockFactoryTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/store/BaseLockFactoryTestCase.javaindex b2ad1781654..b5b3c539f79 100644--- a/lucene/test-framework/src/java/org/apache/lucene/store/BaseLockFactoryTestCase.java+++ b/lucene/test-framework/src/java/org/apache/lucene/store/BaseLockFactoryTestCase.java@@ -21,6 +21,7 @@ import java.io.IOException;import java.io.PrintStream;import java.io.UnsupportedEncodingException;import java.nio.file.AccessDeniedException;+import java.nio.file.NoSuchFileException;import java.nio.file.Path;import java.util.concurrent.CyclicBarrier;import java.util.concurrent.atomic.AtomicBoolean;@@ -58,10 +59,10 @@ public abstract class BaseLockFactoryTestCase extends LuceneTestCase {Directory dir = getDirectory(tempPath);Lock l = dir.obtainLock("commit");- try {+ // shouldn't be able to get the lock twice+ expectThrows(LockObtainFailedException.class, () -> {dir.obtainLock("commit");- fail("succeeded in obtaining lock twice, didn't get exception");- } catch (LockObtainFailedException expected) {}+ });l.close();// Make sure we can obtain first one again:@@ -101,10 +102,10 @@ public abstract class BaseLockFactoryTestCase extends LuceneTestCase {Lock l = dir.obtainLock("commit");l.close();- try {+ expectThrows(AlreadyClosedException.class, () -> {l.ensureValid();- fail("didn't get exception");- } catch (AlreadyClosedException expected) {}+ });+dir.close();}