You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2018/04/08 15:42:20 UTC
[1/4] [text] Update tests from JUnit 4 to 5. Closes #79.
Repository: commons-text
Updated Branches:
refs/heads/master 6f06de9eb -> 49db4cb38
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/lookup/MapStringLookupTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/lookup/MapStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/MapStringLookupTest.java
index 5e7d1b7..7ff7d58 100644
--- a/src/test/java/org/apache/commons/text/lookup/MapStringLookupTest.java
+++ b/src/test/java/org/apache/commons/text/lookup/MapStringLookupTest.java
@@ -1,37 +1,37 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache license, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the license for the specific language governing permissions and
- * limitations under the license.
- */
-
-package org.apache.commons.text.lookup;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-public class MapStringLookupTest {
-
- @Test
- public void testOne() {
- final String key = "key";
- final String value = "value";
- final Map<String, String> map = new HashMap<>();
- map.put(key, value);
- Assert.assertEquals(value, MapStringLookup.on(map).lookup(key));
- }
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+
+package org.apache.commons.text.lookup;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class MapStringLookupTest {
+
+ @Test
+ public void testOne() {
+ final String key = "key";
+ final String value = "value";
+ final Map<String, String> map = new HashMap<>();
+ map.put(key, value);
+ Assertions.assertEquals(value, MapStringLookup.on(map).lookup(key));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/lookup/NullStringLookupTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/lookup/NullStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/NullStringLookupTest.java
index 2efde17..361d97b 100644
--- a/src/test/java/org/apache/commons/text/lookup/NullStringLookupTest.java
+++ b/src/test/java/org/apache/commons/text/lookup/NullStringLookupTest.java
@@ -1,30 +1,30 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache license, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the license for the specific language governing permissions and
- * limitations under the license.
- */
-
-package org.apache.commons.text.lookup;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-public class NullStringLookupTest {
-
- @Test
- public void test() {
- Assert.assertEquals(null, NullStringLookup.INSTANCE.lookup("EverythingIsNull"));
- }
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+
+package org.apache.commons.text.lookup;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class NullStringLookupTest {
+
+ @Test
+ public void test() {
+ Assertions.assertEquals(null, NullStringLookup.INSTANCE.lookup("EverythingIsNull"));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/lookup/ResourceBundleStringLookupTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/lookup/ResourceBundleStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/ResourceBundleStringLookupTest.java
index a9357da..37415b5 100644
--- a/src/test/java/org/apache/commons/text/lookup/ResourceBundleStringLookupTest.java
+++ b/src/test/java/org/apache/commons/text/lookup/ResourceBundleStringLookupTest.java
@@ -1,35 +1,35 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache license, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the license for the specific language governing permissions and
- * limitations under the license.
- */
-
-package org.apache.commons.text.lookup;
-
-import java.util.ResourceBundle;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-public class ResourceBundleStringLookupTest {
-
- @Test
- public void testOne() {
- final String bundleName = "testResourceBundleLookup";
- final String bundleKey = "key";
- Assert.assertEquals(ResourceBundle.getBundle(bundleName).getString(bundleKey),
- ResourceBundleStringLookup.INSTANCE.lookup(bundleName + ":" + bundleKey));
- }
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+
+package org.apache.commons.text.lookup;
+
+import java.util.ResourceBundle;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class ResourceBundleStringLookupTest {
+
+ @Test
+ public void testOne() {
+ final String bundleName = "testResourceBundleLookup";
+ final String bundleKey = "key";
+ Assertions.assertEquals(ResourceBundle.getBundle(bundleName).getString(bundleKey),
+ ResourceBundleStringLookup.INSTANCE.lookup(bundleName + ":" + bundleKey));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/lookup/SystemPropertyStringLookupTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/lookup/SystemPropertyStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/SystemPropertyStringLookupTest.java
index 4bfd9c8..2a93f85 100644
--- a/src/test/java/org/apache/commons/text/lookup/SystemPropertyStringLookupTest.java
+++ b/src/test/java/org/apache/commons/text/lookup/SystemPropertyStringLookupTest.java
@@ -1,31 +1,31 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache license, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the license for the specific language governing permissions and
- * limitations under the license.
- */
-
-package org.apache.commons.text.lookup;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-public class SystemPropertyStringLookupTest {
-
- @Test
- public void testUserName() {
- final String key = "user.name";
- Assert.assertEquals(System.getProperty(key), SystemPropertyStringLookup.INSTANCE.lookup(key));
- }
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+
+package org.apache.commons.text.lookup;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class SystemPropertyStringLookupTest {
+
+ @Test
+ public void testUserName() {
+ final String key = "user.name";
+ Assertions.assertEquals(System.getProperty(key), SystemPropertyStringLookup.INSTANCE.lookup(key));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/matcher/StringMatcherTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/matcher/StringMatcherTest.java b/src/test/java/org/apache/commons/text/matcher/StringMatcherTest.java
index 6dcd792..e4d4902 100644
--- a/src/test/java/org/apache/commons/text/matcher/StringMatcherTest.java
+++ b/src/test/java/org/apache/commons/text/matcher/StringMatcherTest.java
@@ -18,7 +18,7 @@ package org.apache.commons.text.matcher;
import static org.assertj.core.api.Assertions.assertThat;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link StringMatcher}.
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/matcher/StringSubstitutorGetSetTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/matcher/StringSubstitutorGetSetTest.java b/src/test/java/org/apache/commons/text/matcher/StringSubstitutorGetSetTest.java
index 733c853..cee1caa 100644
--- a/src/test/java/org/apache/commons/text/matcher/StringSubstitutorGetSetTest.java
+++ b/src/test/java/org/apache/commons/text/matcher/StringSubstitutorGetSetTest.java
@@ -17,13 +17,13 @@
package org.apache.commons.text.matcher;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import org.apache.commons.text.StringSubstitutor;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Test class for {@link StringSubstitutor}.
@@ -44,7 +44,7 @@ public class StringSubstitutorGetSetTest {
assertTrue(sub.getVariablePrefixMatcher() instanceof AbstractStringMatcher.StringMatcher);
try {
sub.setVariablePrefix((String) null);
- fail();
+ fail("Exception expected!");
} catch (final IllegalArgumentException ex) {
// expected
}
@@ -55,7 +55,7 @@ public class StringSubstitutorGetSetTest {
assertSame(matcher, sub.getVariablePrefixMatcher());
try {
sub.setVariablePrefixMatcher((StringMatcher) null);
- fail();
+ fail("Exception expected!");
} catch (final IllegalArgumentException ex) {
// expected
}
@@ -76,7 +76,7 @@ public class StringSubstitutorGetSetTest {
assertTrue(sub.getVariableSuffixMatcher() instanceof AbstractStringMatcher.StringMatcher);
try {
sub.setVariableSuffix((String) null);
- fail();
+ fail("Exception expected!");
} catch (final IllegalArgumentException ex) {
// expected
}
@@ -87,7 +87,7 @@ public class StringSubstitutorGetSetTest {
assertSame(matcher, sub.getVariableSuffixMatcher());
try {
sub.setVariableSuffixMatcher((StringMatcher) null);
- fail();
+ fail("Exception expected!");
} catch (final IllegalArgumentException ex) {
// expected
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/similarity/CosineDistanceTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/similarity/CosineDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/CosineDistanceTest.java
index 51f7194..62a7619 100644
--- a/src/test/java/org/apache/commons/text/similarity/CosineDistanceTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/CosineDistanceTest.java
@@ -21,8 +21,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import java.math.RoundingMode;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link CosineSimilarity}.
@@ -37,7 +37,7 @@ public class CosineDistanceTest {
/**
* Creates the cosine distance object used throughout the tests.
*/
- @BeforeClass
+ @BeforeAll
public static void setUp() {
cosineDistance = new CosineDistance();
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/similarity/CosineSimilarityTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/similarity/CosineSimilarityTest.java b/src/test/java/org/apache/commons/text/similarity/CosineSimilarityTest.java
index 235d2e3..c229cb5 100644
--- a/src/test/java/org/apache/commons/text/similarity/CosineSimilarityTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/CosineSimilarityTest.java
@@ -17,11 +17,12 @@
package org.apache.commons.text.similarity;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.within;
@@ -38,17 +39,21 @@ public class CosineSimilarityTest {
assertThat(cosineSimilarity.cosineSimilarity(hashMap, hashMapTwo)).isEqualTo(0.0, within(0.01));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testCosineSimilarityThrowsIllegalArgumentException() {
- final CosineSimilarity cosineSimilarity = new CosineSimilarity();
- final Map<CharSequence, Integer> map = new HashMap<>();
- cosineSimilarity.cosineSimilarity(map, null);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ final CosineSimilarity cosineSimilarity = new CosineSimilarity();
+ final Map<CharSequence, Integer> map = new HashMap<>();
+ cosineSimilarity.cosineSimilarity(map, null);
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testCosineSimilarityWithNull() {
- final CosineSimilarity cosineSimilarity = new CosineSimilarity();
- cosineSimilarity.cosineSimilarity(null, null);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ final CosineSimilarity cosineSimilarity = new CosineSimilarity();
+ cosineSimilarity.cosineSimilarity(null, null);
+ });
}
@Test
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/similarity/FuzzyScoreTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/similarity/FuzzyScoreTest.java b/src/test/java/org/apache/commons/text/similarity/FuzzyScoreTest.java
index a6ca81f..53042eb 100644
--- a/src/test/java/org/apache/commons/text/similarity/FuzzyScoreTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/FuzzyScoreTest.java
@@ -17,10 +17,11 @@
package org.apache.commons.text.similarity;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import java.util.Locale;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link FuzzyScore}.
@@ -40,24 +41,32 @@ public class FuzzyScoreTest {
assertThat(ENGLISH_SCORE.fuzzyScore("Apache Software Foundation", "asf")).isEqualTo(3);
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGetFuzzyScore_StringNullLocale() {
- ENGLISH_SCORE.fuzzyScore("not null", null);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ ENGLISH_SCORE.fuzzyScore("not null", null);
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGetFuzzyScore_NullStringLocale() {
- ENGLISH_SCORE.fuzzyScore(null, "not null");
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ ENGLISH_SCORE.fuzzyScore(null, "not null");
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGetFuzzyScore_NullNullLocale() {
- ENGLISH_SCORE.fuzzyScore(null, null);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ ENGLISH_SCORE.fuzzyScore(null, null);
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testMissingLocale() {
- new FuzzyScore((Locale) null);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ new FuzzyScore((Locale) null);
+ });
}
@Test
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/similarity/HammingDistanceTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/similarity/HammingDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/HammingDistanceTest.java
index 6ce2314..edad76a 100644
--- a/src/test/java/org/apache/commons/text/similarity/HammingDistanceTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/HammingDistanceTest.java
@@ -17,9 +17,10 @@
package org.apache.commons.text.similarity;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link HammingDistance}.
@@ -28,7 +29,7 @@ public class HammingDistanceTest {
private static HammingDistance distance;
- @BeforeClass
+ @BeforeAll
public static void setUp() {
distance = new HammingDistance();
}
@@ -45,14 +46,18 @@ public class HammingDistanceTest {
assertThat(distance.apply("ATCG", "ACCC")).isEqualTo(2);
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testHammingDistance_nullLeftValue() {
- distance.apply(null, "");
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ distance.apply(null, "");
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testHammingDistance_nullRightValue() {
- distance.apply("", null);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ distance.apply("", null);
+ });
}
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/similarity/JaccardDistanceTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/similarity/JaccardDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/JaccardDistanceTest.java
index c8e5c61..56d4909 100644
--- a/src/test/java/org/apache/commons/text/similarity/JaccardDistanceTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/JaccardDistanceTest.java
@@ -16,10 +16,11 @@
*/
package org.apache.commons.text.similarity;
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link JaccardDistance}.
@@ -28,41 +29,48 @@ public class JaccardDistanceTest {
private static JaccardDistance classBeingTested;
- @BeforeClass
+ @BeforeAll
public static void setUp() {
classBeingTested = new JaccardDistance();
}
@Test
public void testGettingJaccardDistance() {
- assertEquals(1.00d, classBeingTested.apply("", ""), 0.0d);
- assertEquals(1.00d, classBeingTested.apply("left", ""), 0.0d);
- assertEquals(1.00d, classBeingTested.apply("", "right"), 0.0d);
- assertEquals(0.25d, classBeingTested.apply("frog", "fog"), 0.0d);
- assertEquals(1.00d, classBeingTested.apply("fly", "ant"), 0.0d);
- assertEquals(0.78d, classBeingTested.apply("elephant", "hippo"), 0.0d);
- assertEquals(0.36d, classBeingTested.apply("ABC Corporation", "ABC Corp"), 0.0d);
- assertEquals(0.24d, classBeingTested.apply("D N H Enterprises Inc", "D & H Enterprises, Inc."), 0.0d);
- assertEquals(0.11d,
- classBeingTested.apply("My Gym Children's Fitness Center", "My Gym. Childrens Fitness"), 0.0d);
- assertEquals(0.10d, classBeingTested.apply("PENNSYLVANIA", "PENNCISYLVNIA"), 0.0d);
- assertEquals(0.87d, classBeingTested.apply("left", "right"), 0.0d);
- assertEquals(0.87d, classBeingTested.apply("leettteft", "ritttght"), 0.0d);
- assertEquals(0.0d, classBeingTested.apply("the same string", "the same string"), 0.0d);
+ assertEquals(1.00d, classBeingTested.apply("", ""), 0.00000000000000000001d);
+ assertEquals(1.00d, classBeingTested.apply("left", ""), 0.00000000000000000001d);
+ assertEquals(1.00d, classBeingTested.apply("", "right"), 0.00000000000000000001d);
+ assertEquals(0.25d, classBeingTested.apply("frog", "fog"), 0.00000000000000000001d);
+ assertEquals(1.00d, classBeingTested.apply("fly", "ant"), 0.00000000000000000001d);
+ assertEquals(0.78d, classBeingTested.apply("elephant", "hippo"), 0.00000000000000000001d);
+ assertEquals(0.36d, classBeingTested.apply("ABC Corporation", "ABC Corp"), 0.00000000000000000001d);
+ assertEquals(0.24d, classBeingTested.apply("D N H Enterprises Inc", "D & H Enterprises, Inc."),
+ 0.00000000000000000001d);
+ assertEquals(0.11d, classBeingTested.apply("My Gym Children's Fitness Center", "My Gym. Childrens Fitness"),
+ 0.00000000000000000001d);
+ assertEquals(0.10d, classBeingTested.apply("PENNSYLVANIA", "PENNCISYLVNIA"), 0.00000000000000000001d);
+ assertEquals(0.87d, classBeingTested.apply("left", "right"), 0.00000000000000000001d);
+ assertEquals(0.87d, classBeingTested.apply("leettteft", "ritttght"), 0.00000000000000000001d);
+ assertEquals(0.0d, classBeingTested.apply("the same string", "the same string"), 0.00000000000000000001d);
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGettingJaccardDistanceNullNull() {
- classBeingTested.apply(null, null);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ classBeingTested.apply(null, null);
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGettingJaccardDistanceStringNull() {
- classBeingTested.apply(" ", null);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ classBeingTested.apply(" ", null);
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGettingJaccardDistanceNullString() {
- classBeingTested.apply(null, "right");
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ classBeingTested.apply(null, "right");
+ });
}
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/similarity/JaccardSimilarityTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/similarity/JaccardSimilarityTest.java b/src/test/java/org/apache/commons/text/similarity/JaccardSimilarityTest.java
index 6bbbd2f..c96d6d3 100644
--- a/src/test/java/org/apache/commons/text/similarity/JaccardSimilarityTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/JaccardSimilarityTest.java
@@ -16,10 +16,11 @@
*/
package org.apache.commons.text.similarity;
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link JaccardSimilarity}.
@@ -28,41 +29,48 @@ public class JaccardSimilarityTest {
private static JaccardSimilarity classBeingTested;
- @BeforeClass
+ @BeforeAll
public static void setUp() {
classBeingTested = new JaccardSimilarity();
}
@Test
public void testGettingJaccardSimilarity() {
- assertEquals(0.00d, classBeingTested.apply("", ""), 0.0d);
- assertEquals(0.00d, classBeingTested.apply("left", ""), 0.0d);
- assertEquals(0.00d, classBeingTested.apply("", "right"), 0.0d);
- assertEquals(0.75d, classBeingTested.apply("frog", "fog"), 0.0d);
- assertEquals(0.00d, classBeingTested.apply("fly", "ant"), 0.0d);
- assertEquals(0.22d, classBeingTested.apply("elephant", "hippo"), 0.0d);
- assertEquals(0.64d, classBeingTested.apply("ABC Corporation", "ABC Corp"), 0.0d);
- assertEquals(0.76d, classBeingTested.apply("D N H Enterprises Inc", "D & H Enterprises, Inc."), 0.0d);
- assertEquals(0.89d,
- classBeingTested.apply("My Gym Children's Fitness Center", "My Gym. Childrens Fitness"), 0.0d);
- assertEquals(0.9d, classBeingTested.apply("PENNSYLVANIA", "PENNCISYLVNIA"), 0.0d);
- assertEquals(0.13d, classBeingTested.apply("left", "right"), 0.0d);
- assertEquals(0.13d, classBeingTested.apply("leettteft", "ritttght"), 0.0d);
- assertEquals(1.0d, classBeingTested.apply("the same string", "the same string"), 0.0d);
+ assertEquals(0.00d, classBeingTested.apply("", ""), 0.00000000000000000001d);
+ assertEquals(0.00d, classBeingTested.apply("left", ""), 0.00000000000000000001d);
+ assertEquals(0.00d, classBeingTested.apply("", "right"), 0.00000000000000000001d);
+ assertEquals(0.75d, classBeingTested.apply("frog", "fog"), 0.00000000000000000001d);
+ assertEquals(0.00d, classBeingTested.apply("fly", "ant"), 0.00000000000000000001d);
+ assertEquals(0.22d, classBeingTested.apply("elephant", "hippo"), 0.00000000000000000001d);
+ assertEquals(0.64d, classBeingTested.apply("ABC Corporation", "ABC Corp"), 0.00000000000000000001d);
+ assertEquals(0.76d, classBeingTested.apply("D N H Enterprises Inc", "D & H Enterprises, Inc."),
+ 0.00000000000000000001d);
+ assertEquals(0.89d, classBeingTested.apply("My Gym Children's Fitness Center", "My Gym. Childrens Fitness"),
+ 0.00000000000000000001d);
+ assertEquals(0.9d, classBeingTested.apply("PENNSYLVANIA", "PENNCISYLVNIA"), 0.00000000000000000001d);
+ assertEquals(0.13d, classBeingTested.apply("left", "right"), 0.00000000000000000001d);
+ assertEquals(0.13d, classBeingTested.apply("leettteft", "ritttght"), 0.00000000000000000001d);
+ assertEquals(1.0d, classBeingTested.apply("the same string", "the same string"), 0.00000000000000000001d);
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGettingJaccardSimilarityNullNull() {
- classBeingTested.apply(null, null);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ classBeingTested.apply(null, null);
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGettingJaccardSimilarityStringNull() {
- classBeingTested.apply(" ", null);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ classBeingTested.apply(" ", null);
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGettingJaccardSimilarityNullString() {
- classBeingTested.apply(null, "right");
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ classBeingTested.apply(null, "right");
+ });
}
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/similarity/JaroWinklerDistanceTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/similarity/JaroWinklerDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/JaroWinklerDistanceTest.java
index 1c94e7f..d51135e 100644
--- a/src/test/java/org/apache/commons/text/similarity/JaroWinklerDistanceTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/JaroWinklerDistanceTest.java
@@ -16,10 +16,11 @@
*/
package org.apache.commons.text.similarity;
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link JaroWinklerDistance}.
@@ -28,7 +29,7 @@ public class JaroWinklerDistanceTest {
private static JaroWinklerDistance distance;
- @BeforeClass
+ @BeforeAll
public static void setUp() {
distance = new JaroWinklerDistance();
}
@@ -36,7 +37,7 @@ public class JaroWinklerDistanceTest {
@Test
public void testGetJaroWinklerDistance_StringString() {
assertEquals(0.92499d, distance.apply("frog", "fog"), 0.00001d);
- assertEquals(0.0d, distance.apply("fly", "ant"), 0.0d);
+ assertEquals(0.0d, distance.apply("fly", "ant"), 0.00000000000000000001d);
assertEquals(0.44166d, distance.apply("elephant", "hippo"), 0.00001d);
assertEquals(0.92740d, distance.apply("ABC Corporation", "ABC Corp"), 0.00001d);
assertEquals(0.94580d, distance.apply("D N H Enterprises Inc", "D & H Enterprises, Inc."), 0.00001d);
@@ -46,19 +47,25 @@ public class JaroWinklerDistanceTest {
assertEquals(0.996598d, distance.apply("/opt/software1", "/opt/software2"), 0.00001d);
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGetJaroWinklerDistance_NullNull() {
- distance.apply(null, null);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ distance.apply(null, null);
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGetJaroWinklerDistance_StringNull() {
- distance.apply(" ", null);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ distance.apply(" ", null);
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGetJaroWinklerDistance_NullString() {
- distance.apply(null, "clear");
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ distance.apply(null, "clear");
+ });
}
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/similarity/LevenshteinDetailedDistanceTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/similarity/LevenshteinDetailedDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/LevenshteinDetailedDistanceTest.java
index 1d1c2ca..1641cbb 100644
--- a/src/test/java/org/apache/commons/text/similarity/LevenshteinDetailedDistanceTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/LevenshteinDetailedDistanceTest.java
@@ -17,9 +17,10 @@
package org.apache.commons.text.similarity;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import org.apache.commons.text.TextStringBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class LevenshteinDetailedDistanceTest {
@@ -137,14 +138,14 @@ public class LevenshteinDetailedDistanceTest {
assertThat(expectedResult.toString()).isEqualTo(actualResult.toString());
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGetLevenshteinDetailedDistance_NullString() {
- UNLIMITED_DISTANCE.apply("a", null);
+ assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply("a", null));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGetLevenshteinDetailedDistance_StringNull() {
- UNLIMITED_DISTANCE.apply(null, "a");
+ assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply(null, "a"));
}
@Test
@@ -386,19 +387,19 @@ public class LevenshteinDetailedDistanceTest {
assertThat(result.getSubstituteCount()).isEqualTo(1);
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGetLevenshteinDetailedDistance_NullStringInt() {
- UNLIMITED_DISTANCE.apply(null, "a");
+ assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply(null, "a"));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGetLevenshteinDetailedDistance_StringNullInt() {
- UNLIMITED_DISTANCE.apply("a", null);
+ assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply("a", null));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testConstructorWithNegativeThreshold() {
- new LevenshteinDetailedDistance(-1);
+ assertThatIllegalArgumentException().isThrownBy(() -> new LevenshteinDetailedDistance(-1));
}
@Test
@@ -436,17 +437,19 @@ public class LevenshteinDetailedDistanceTest {
assertThat(levenshteinResults.getDistance()).isEqualTo(-1);
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testApplyThrowsIllegalArgumentExceptionAndCreatesLevenshteinDetailedDistanceTakingInteger() {
- final LevenshteinDetailedDistance levenshteinDetailedDistance = new LevenshteinDetailedDistance(0);
- final CharSequence charSequence = new TextStringBuilder();
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ final LevenshteinDetailedDistance levenshteinDetailedDistance = new LevenshteinDetailedDistance(0);
+ final CharSequence charSequence = new TextStringBuilder();
- levenshteinDetailedDistance.apply(charSequence, null);
+ levenshteinDetailedDistance.apply(charSequence, null);
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testApplyWithNull() {
- new LevenshteinDetailedDistance(0).apply(null, null);
+ assertThatIllegalArgumentException().isThrownBy(() -> new LevenshteinDetailedDistance(0).apply(null, null));
}
@Test
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/similarity/LevenshteinDistanceTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/similarity/LevenshteinDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/LevenshteinDistanceTest.java
index 3696810..45ee27e 100644
--- a/src/test/java/org/apache/commons/text/similarity/LevenshteinDistanceTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/LevenshteinDistanceTest.java
@@ -16,9 +16,10 @@
*/
package org.apache.commons.text.similarity;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Unit tests for {@link LevenshteinDistance}.
@@ -41,14 +42,14 @@ public class LevenshteinDistanceTest {
assertThat(UNLIMITED_DISTANCE.apply("hello", "hallo")).isEqualTo(1);
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGetLevenshteinDistance_NullString() {
- UNLIMITED_DISTANCE.apply("a", null);
+ assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply("a", null));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGetLevenshteinDistance_StringNull() {
- UNLIMITED_DISTANCE.apply(null, "a");
+ assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply(null, "a"));
}
@Test
@@ -115,24 +116,24 @@ public class LevenshteinDistanceTest {
assertThat(new LevenshteinDistance(Integer.MAX_VALUE).apply("hello", "hallo")).isEqualTo(1);
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGetLevenshteinDistance_NullStringInt() {
- UNLIMITED_DISTANCE.apply(null, "a");
+ assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply(null, "a"));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGetLevenshteinDistance_StringNullInt() {
- UNLIMITED_DISTANCE.apply("a", null);
+ assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply("a", null));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testConstructorWithNegativeThreshold() {
- new LevenshteinDistance(-1);
+ assertThatIllegalArgumentException().isThrownBy(() -> new LevenshteinDistance(-1));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testApplyThrowsIllegalArgumentExceptionAndCreatesLevenshteinDistanceTakingInteger() {
- new LevenshteinDistance(0).apply(null, null);
+ assertThatIllegalArgumentException().isThrownBy(() -> new LevenshteinDistance(0).apply(null, null));
}
@Test
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/similarity/LevenshteinResultsTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/similarity/LevenshteinResultsTest.java b/src/test/java/org/apache/commons/text/similarity/LevenshteinResultsTest.java
index 8417b6f..3c113c6 100644
--- a/src/test/java/org/apache/commons/text/similarity/LevenshteinResultsTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/LevenshteinResultsTest.java
@@ -16,7 +16,7 @@
*/
package org.apache.commons.text.similarity;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceDistanceTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceDistanceTest.java
index 5345bdd..b0a8977 100644
--- a/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceDistanceTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceDistanceTest.java
@@ -16,10 +16,11 @@
*/
package org.apache.commons.text.similarity;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Unit tests for {@link LongestCommonSubsequenceDistance}.
@@ -28,7 +29,7 @@ public class LongestCommonSubsequenceDistanceTest {
private static LongestCommonSubsequenceDistance subject;
- @BeforeClass
+ @BeforeAll
public static void setup() {
subject = new LongestCommonSubsequenceDistance();
}
@@ -50,19 +51,19 @@ public class LongestCommonSubsequenceDistanceTest {
assertThat(subject.apply("the same string", "the same string")).isEqualTo(0);
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGettingLongestCommonSubsequenceDistanceNullNull() {
- subject.apply(null, null);
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(null, null));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGettingLongestCommonSubsequenceDistanceStringNull() {
- subject.apply(" ", null);
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(" ", null));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGettingLongestCommonSubsequenceDistanceNullString() {
- subject.apply(null, "right");
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(null, "right"));
}
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceTest.java b/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceTest.java
index 7aace1f..19b73a4 100644
--- a/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceTest.java
@@ -16,10 +16,11 @@
*/
package org.apache.commons.text.similarity;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Unit tests for {@link LongestCommonSubsequence}.
@@ -28,7 +29,7 @@ public class LongestCommonSubsequenceTest {
private static LongestCommonSubsequence subject;
- @BeforeClass
+ @BeforeAll
public static void setup() {
subject = new LongestCommonSubsequence();
}
@@ -50,19 +51,19 @@ public class LongestCommonSubsequenceTest {
assertThat(subject.apply("the same string", "the same string")).isEqualTo(15);
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGettingLongestCommonSubsequenceApplyNullNull() {
- subject.apply(null, null);
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(null, null));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGettingLongestCommonSubsequenceApplyStringNull() {
- subject.apply(" ", null);
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(" ", null));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGettingLongestCommonSubsequenceApplyNullString() {
- subject.apply(null, "right");
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(null, "right"));
}
@Test
@@ -84,19 +85,19 @@ public class LongestCommonSubsequenceTest {
assertThat(subject.longestCommonSubsequence("the same string", "the same string")).isEqualTo("the same string");
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGettingLongestCommonSubsequenceNullNull() {
- subject.longestCommonSubsequence(null, null);
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.longestCommonSubsequence(null, null));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGettingLongestCommonSubsequenceStringNull() {
- subject.longestCommonSubsequence(" ", null);
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.longestCommonSubsequence(" ", null));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGettingLongestCommonSubsequenceNullString() {
- subject.longestCommonSubsequence(null, "right");
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.longestCommonSubsequence(null, "right"));
}
@Test
@@ -119,21 +120,21 @@ public class LongestCommonSubsequenceTest {
assertThat(subject.logestCommonSubsequence("the same string", "the same string")).isEqualTo("the same string");
}
- @Test(expected = IllegalArgumentException.class)
- @Deprecated
+ @Test
+ @SuppressWarnings("deprecation")
public void testGettingLogestCommonSubsequenceNullNull() {
- subject.logestCommonSubsequence(null, null);
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.logestCommonSubsequence(null, null));
}
- @Test(expected = IllegalArgumentException.class)
- @Deprecated
+ @Test
+ @SuppressWarnings("deprecation")
public void testGettingLogestCommonSubsequenceStringNull() {
- subject.logestCommonSubsequence(" ", null);
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.logestCommonSubsequence(" ", null));
}
- @Test(expected = IllegalArgumentException.class)
- @Deprecated
+ @Test
+ @SuppressWarnings("deprecation")
public void testGettingLogestCommonSubsequenceNullString() {
- subject.logestCommonSubsequence(null, "right");
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.logestCommonSubsequence(null, "right"));
}
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/similarity/ParameterizedEditDistanceFromTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/similarity/ParameterizedEditDistanceFromTest.java b/src/test/java/org/apache/commons/text/similarity/ParameterizedEditDistanceFromTest.java
index 8e0582e..721439b 100644
--- a/src/test/java/org/apache/commons/text/similarity/ParameterizedEditDistanceFromTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/ParameterizedEditDistanceFromTest.java
@@ -16,75 +16,53 @@
*/
package org.apache.commons.text.similarity;
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
-import java.util.Arrays;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
/**
* Unit tests for {@link EditDistanceFrom}.
*
* @param <R> The {@link EditDistance} return type.
*/
-@RunWith(Parameterized.class)
public class ParameterizedEditDistanceFromTest<R> {
- private final EditDistance<R> editDistance;
- private final CharSequence left;
- private final CharSequence right;
- private final R distance;
-
- public ParameterizedEditDistanceFromTest(
- final EditDistance<R> editDistance,
- final CharSequence left, final CharSequence right,
- final R distance) {
-
- this.editDistance = editDistance;
- this.left = left;
- this.right = right;
- this.distance = distance;
- }
-
- @Parameters
- public static Iterable<Object[]> parameters() {
- return Arrays.asList(new Object[][] {
-
- {new HammingDistance(), "Sam I am.", "Ham I am.", 1},
- {new HammingDistance(), "Japtheth, Ham, Shem", "Japtheth, HAM, Shem", 2},
- {new HammingDistance(), "Hamming", "Hamming", 0},
-
- {new LevenshteinDistance(), "Apache", "a patchy", 4},
- {new LevenshteinDistance(), "go", "no go", 3},
- {new LevenshteinDistance(), "go", "go", 0},
+ public static Stream<Arguments> parameters() {
+ return Stream.of(
+ Arguments.of(new HammingDistance(), "Sam I am.", "Ham I am.", 1),
+ Arguments.of(new HammingDistance(), "Japtheth, Ham, Shem", "Japtheth, HAM, Shem", 2),
+ Arguments.of(new HammingDistance(), "Hamming", "Hamming", 0),
- {new LevenshteinDistance(4), "Apache", "a patchy", 4},
- {new LevenshteinDistance(4), "go", "no go", 3},
- {new LevenshteinDistance(0), "go", "go", 0},
+ Arguments.of(new LevenshteinDistance(), "Apache", "a patchy", 4),
+ Arguments.of(new LevenshteinDistance(), "go", "no go", 3),
+ Arguments.of(new LevenshteinDistance(), "go", "go", 0),
- {
- new EditDistance<Boolean>() {
- @Override
- public Boolean apply(final CharSequence left, final CharSequence right) {
- return left == right || (left != null && left.equals(right));
- }
- },
- "Bob's your uncle.",
- "Every good boy does fine.",
- false
- }
+ Arguments.of(new LevenshteinDistance(4), "Apache", "a patchy", 4),
+ Arguments.of(new LevenshteinDistance(4), "go", "no go", 3),
+ Arguments.of(new LevenshteinDistance(0), "go", "go", 0),
- });
+ Arguments.of(
+ new EditDistance<Boolean>() {
+ @Override
+ public Boolean apply(final CharSequence left, final CharSequence right) {
+ return left == right || (left != null && left.equals(right));
+ }
+ },
+ "Bob's your uncle.",
+ "Every good boy does fine.",
+ false));
}
- @Test
- public void test() {
+ @ParameterizedTest
+ @MethodSource("parameters")
+ public void test(EditDistance<R> editDistance, CharSequence left, CharSequence right, R distance) {
final EditDistanceFrom<R> editDistanceFrom = new EditDistanceFrom<>(editDistance, left);
- assertThat(editDistanceFrom.apply(right), equalTo(distance));
+ assertThat(editDistanceFrom.apply(right)).isEqualTo(distance);
}
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/similarity/ParameterizedLevenshteinDistanceTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/similarity/ParameterizedLevenshteinDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/ParameterizedLevenshteinDistanceTest.java
index 0310171..3189ca3 100644
--- a/src/test/java/org/apache/commons/text/similarity/ParameterizedLevenshteinDistanceTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/ParameterizedLevenshteinDistanceTest.java
@@ -16,109 +16,88 @@
*/
package org.apache.commons.text.similarity;
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
-import java.util.Arrays;
+import java.util.stream.Stream;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
/**
* Unit tests for {@link LevenshteinDistance}.
*/
-@RunWith(Parameterized.class)
public class ParameterizedLevenshteinDistanceTest {
- private final Integer distance;
- private final CharSequence left;
- private final CharSequence right;
- private final Integer threshold;
-
- public ParameterizedLevenshteinDistanceTest(
- final Integer threshold,
- final CharSequence left, final CharSequence right,
- final Integer distance) {
-
- this.threshold = threshold;
- this.left = left;
- this.right = right;
- this.distance = distance;
- }
-
- @Parameters
- public static Iterable<Object[]> parameters() {
- return Arrays.asList(new Object[][] {
-
+ public static Stream<Arguments> parameters() {
+ return Stream.of(
/* empty strings */
- {0, "", "", 0},
- {8, "aaapppp", "", 7},
- {7, "aaapppp", "", 7},
- {6, "aaapppp", "", -1},
+ Arguments.of(0, "", "", 0),
+ Arguments.of(8, "aaapppp", "", 7),
+ Arguments.of(7, "aaapppp", "", 7),
+ Arguments.of(6, "aaapppp", "", -1),
/* unequal strings, zero threshold */
- {0, "b", "a", -1},
- {0, "a", "b", -1},
+ Arguments.of(0, "b", "a", -1),
+ Arguments.of(0, "a", "b", -1),
/* equal strings */
- {0, "aa", "aa", 0},
- {2, "aa", "aa", 0},
+ Arguments.of(0, "aa", "aa", 0),
+ Arguments.of(2, "aa", "aa", 0),
/* same length */
- {2, "aaa", "bbb", -1},
- {3, "aaa", "bbb", 3},
+ Arguments.of(2, "aaa", "bbb", -1),
+ Arguments.of(3, "aaa", "bbb", 3),
/* big stripe */
- {10, "aaaaaa", "b", 6},
+ Arguments.of(10, "aaaaaa", "b", 6),
/* distance less than threshold */
- {8, "aaapppp", "b", 7},
- {4, "a", "bbb", 3},
+ Arguments.of(8, "aaapppp", "b", 7),
+ Arguments.of(4, "a", "bbb", 3),
/* distance equal to threshold */
- {7, "aaapppp", "b", 7},
- {3, "a", "bbb", 3},
+ Arguments.of(7, "aaapppp", "b", 7),
+ Arguments.of(3, "a", "bbb", 3),
/* distance greater than threshold */
- {2, "a", "bbb", -1},
- {2, "bbb", "a", -1},
- {6, "aaapppp", "b", -1},
+ Arguments.of(2, "a", "bbb", -1),
+ Arguments.of(2, "bbb", "a", -1),
+ Arguments.of(6, "aaapppp", "b", -1),
/* stripe runs off array, strings not similar */
- {1, "a", "bbb", -1},
- {1, "bbb", "a", -1},
+ Arguments.of(1, "a", "bbb", -1),
+ Arguments.of(1, "bbb", "a", -1),
/* stripe runs off array, strings are similar */
- {1, "12345", "1234567", -1},
- {1, "1234567", "12345", -1},
+ Arguments.of(1, "12345", "1234567", -1),
+ Arguments.of(1, "1234567", "12345", -1),
/* old getLevenshteinDistance test cases */
- {1, "frog", "fog", 1},
- {3, "fly", "ant", 3},
- {7, "elephant", "hippo", 7},
- {6, "elephant", "hippo", -1},
- {7, "hippo", "elephant", 7},
- {6, "hippo", "elephant", -1},
- {8, "hippo", "zzzzzzzz", 8},
- {8, "zzzzzzzz", "hippo", 8},
- {1, "hello", "hallo", 1},
-
- {Integer.MAX_VALUE, "frog", "fog", 1},
- {Integer.MAX_VALUE, "fly", "ant", 3},
- {Integer.MAX_VALUE, "elephant", "hippo", 7},
- {Integer.MAX_VALUE, "hippo", "elephant", 7},
- {Integer.MAX_VALUE, "hippo", "zzzzzzzz", 8},
- {Integer.MAX_VALUE, "zzzzzzzz", "hippo", 8},
- {Integer.MAX_VALUE, "hello", "hallo", 1}
- });
+ Arguments.of(1, "frog", "fog", 1),
+ Arguments.of(3, "fly", "ant", 3),
+ Arguments.of(7, "elephant", "hippo", 7),
+ Arguments.of(6, "elephant", "hippo", -1),
+ Arguments.of(7, "hippo", "elephant", 7),
+ Arguments.of(6, "hippo", "elephant", -1),
+ Arguments.of(8, "hippo", "zzzzzzzz", 8),
+ Arguments.of(8, "zzzzzzzz", "hippo", 8),
+ Arguments.of(1, "hello", "hallo", 1),
+
+ Arguments.of(Integer.MAX_VALUE, "frog", "fog", 1),
+ Arguments.of(Integer.MAX_VALUE, "fly", "ant", 3),
+ Arguments.of(Integer.MAX_VALUE, "elephant", "hippo", 7),
+ Arguments.of(Integer.MAX_VALUE, "hippo", "elephant", 7),
+ Arguments.of(Integer.MAX_VALUE, "hippo", "zzzzzzzz", 8),
+ Arguments.of(Integer.MAX_VALUE, "zzzzzzzz", "hippo", 8),
+ Arguments.of(Integer.MAX_VALUE, "hello", "hallo", 1));
}
- @Test
- public void test() {
+ @ParameterizedTest
+ @MethodSource("parameters")
+ public void test(Integer threshold, CharSequence left, CharSequence right, Integer distance) {
final LevenshteinDistance metric = new LevenshteinDistance(threshold);
- assertThat(metric.apply(left, right), equalTo(distance));
+ assertThat(metric.apply(left, right)).isEqualTo(distance);
}
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/similarity/ParameterizedSimilarityScoreFromTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/similarity/ParameterizedSimilarityScoreFromTest.java b/src/test/java/org/apache/commons/text/similarity/ParameterizedSimilarityScoreFromTest.java
index 030cae6..9e30bed 100644
--- a/src/test/java/org/apache/commons/text/similarity/ParameterizedSimilarityScoreFromTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/ParameterizedSimilarityScoreFromTest.java
@@ -16,49 +16,28 @@
*/
package org.apache.commons.text.similarity;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
+import static org.assertj.core.api.Assertions.assertThat;
-import java.util.Arrays;
+import java.util.stream.Stream;
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertThat;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
/**
* Unit tests for {@link SimilarityScoreFrom}.
*
* @param <R> The {@link SimilarityScore} return type.
*/
-@RunWith(Parameterized.class)
public class ParameterizedSimilarityScoreFromTest<R> {
- private final SimilarityScore<R> similarityScore;
- private final CharSequence left;
- private final CharSequence right;
- private final R distance;
+ public static Stream<Arguments> parameters() {
+ return Stream.of(
+ Arguments.of(new LevenshteinDistance(), "elephant", "hippo", 7),
+ Arguments.of(new LevenshteinDistance(), "hippo", "elephant", 7),
+ Arguments.of(new LevenshteinDistance(), "hippo", "zzzzzzzz", 8),
- public ParameterizedSimilarityScoreFromTest(
- final SimilarityScore<R> similarityScore,
- final CharSequence left, final CharSequence right,
- final R distance) {
-
- this.similarityScore = similarityScore;
- this.left = left;
- this.right = right;
- this.distance = distance;
- }
-
- @Parameters
- public static Iterable<Object[]> parameters() {
- return Arrays.asList(new Object[][] {
-
- {new LevenshteinDistance(), "elephant", "hippo", 7},
- {new LevenshteinDistance(), "hippo", "elephant", 7},
- {new LevenshteinDistance(), "hippo", "zzzzzzzz", 8},
-
- {
+ Arguments.of(
new SimilarityScore<Boolean>() {
@Override
public Boolean apply(final CharSequence left, final CharSequence right) {
@@ -68,14 +47,13 @@ public class ParameterizedSimilarityScoreFromTest<R> {
"Bob's your uncle.",
"Every good boy does fine.",
false
- }
-
- });
+ ));
}
- @Test
- public void test() {
+ @ParameterizedTest
+ @MethodSource("parameters")
+ public void test(SimilarityScore<R> similarityScore, CharSequence left, CharSequence right, R distance) {
final SimilarityScoreFrom<R> similarityScoreFrom = new SimilarityScoreFrom<>(similarityScore, left);
- assertThat(similarityScoreFrom.apply(right), equalTo(distance));
+ assertThat(similarityScoreFrom.apply(right)).isEqualTo(distance);
}
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/similarity/SimilarityScoreFromTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/similarity/SimilarityScoreFromTest.java b/src/test/java/org/apache/commons/text/similarity/SimilarityScoreFromTest.java
index 1c8468a..59ad8d0 100644
--- a/src/test/java/org/apache/commons/text/similarity/SimilarityScoreFromTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/SimilarityScoreFromTest.java
@@ -18,14 +18,15 @@
package org.apache.commons.text.similarity;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class SimilarityScoreFromTest {
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testFailsToCreateSimilarityScoreFromThrowsIllegalArgumentException() {
- new SimilarityScoreFrom<>(null, "");
+ assertThatIllegalArgumentException().isThrownBy(() -> new SimilarityScoreFrom<>(null, ""));
}
@Test
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/similarity/StringMetricFromTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/similarity/StringMetricFromTest.java b/src/test/java/org/apache/commons/text/similarity/StringMetricFromTest.java
index 96a54eb..34609f7 100644
--- a/src/test/java/org/apache/commons/text/similarity/StringMetricFromTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/StringMetricFromTest.java
@@ -16,10 +16,10 @@
*/
package org.apache.commons.text.similarity;
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link EditDistanceFrom}.
@@ -34,8 +34,8 @@ public class StringMetricFromTest {
final Integer distance = 4;
final EditDistanceFrom<Integer> metricFrom = new EditDistanceFrom<>(metric, left);
- assertThat(metricFrom.apply(right), equalTo(distance));
- assertThat(metricFrom.apply(right), equalTo(metric.apply(left, right)));
+ assertThat(metricFrom.apply(right)).isEqualTo(distance);
+ assertThat(metricFrom.apply(right)).isEqualTo(metric.apply(left, right));
}
@Test
@@ -54,13 +54,13 @@ public class StringMetricFromTest {
mostSimilar = test;
}
}
- assertThat(mostSimilar, equalTo("a patchy"));
- assertThat(shortestDistance, equalTo(4));
+ assertThat(mostSimilar).isEqualTo("a patchy");
+ assertThat(shortestDistance).isEqualTo(4);
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testMissingMetric() {
- new EditDistanceFrom<Number>(null, "no go");
+ assertThatIllegalArgumentException().isThrownBy(() -> new EditDistanceFrom<Number>(null, "no go"));
}
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/translate/AggregateTranslatorTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/translate/AggregateTranslatorTest.java b/src/test/java/org/apache/commons/text/translate/AggregateTranslatorTest.java
index 55d9c3f..fba9516 100644
--- a/src/test/java/org/apache/commons/text/translate/AggregateTranslatorTest.java
+++ b/src/test/java/org/apache/commons/text/translate/AggregateTranslatorTest.java
@@ -16,7 +16,7 @@
*/
package org.apache.commons.text.translate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.StringWriter;
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/translate/CodePointTranslatorTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/translate/CodePointTranslatorTest.java b/src/test/java/org/apache/commons/text/translate/CodePointTranslatorTest.java
index 6995f67..3adbc8e 100644
--- a/src/test/java/org/apache/commons/text/translate/CodePointTranslatorTest.java
+++ b/src/test/java/org/apache/commons/text/translate/CodePointTranslatorTest.java
@@ -16,7 +16,7 @@
*/
package org.apache.commons.text.translate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.PipedReader;
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/translate/CsvTranslatorsTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/translate/CsvTranslatorsTest.java b/src/test/java/org/apache/commons/text/translate/CsvTranslatorsTest.java
index 231a8d6..ab7393f 100644
--- a/src/test/java/org/apache/commons/text/translate/CsvTranslatorsTest.java
+++ b/src/test/java/org/apache/commons/text/translate/CsvTranslatorsTest.java
@@ -23,7 +23,7 @@ import java.io.StringWriter;
import java.io.Writer;
import org.apache.commons.lang3.CharUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class CsvTranslatorsTest {
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/translate/EntityArraysTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/translate/EntityArraysTest.java b/src/test/java/org/apache/commons/text/translate/EntityArraysTest.java
index 9140a48..49528d0 100644
--- a/src/test/java/org/apache/commons/text/translate/EntityArraysTest.java
+++ b/src/test/java/org/apache/commons/text/translate/EntityArraysTest.java
@@ -17,7 +17,7 @@
package org.apache.commons.text.translate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.FileReader;
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/translate/JavaUnicodeEscaperTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/translate/JavaUnicodeEscaperTest.java b/src/test/java/org/apache/commons/text/translate/JavaUnicodeEscaperTest.java
index 88ad32f..6f547a3 100644
--- a/src/test/java/org/apache/commons/text/translate/JavaUnicodeEscaperTest.java
+++ b/src/test/java/org/apache/commons/text/translate/JavaUnicodeEscaperTest.java
@@ -16,7 +16,7 @@
*/
package org.apache.commons.text.translate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/translate/LookupTranslatorTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/translate/LookupTranslatorTest.java b/src/test/java/org/apache/commons/text/translate/LookupTranslatorTest.java
index 77b671f..868ea40 100644
--- a/src/test/java/org/apache/commons/text/translate/LookupTranslatorTest.java
+++ b/src/test/java/org/apache/commons/text/translate/LookupTranslatorTest.java
@@ -17,7 +17,7 @@
package org.apache.commons.text.translate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.StringWriter;
@@ -26,6 +26,7 @@ import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Unit tests for {@link LookupTranslator}.
@@ -55,9 +56,9 @@ public class LookupTranslatorTest {
assertThat(out.toString()).as("Incorrect value").isEqualTo("two");
}
- @Test(expected = InvalidParameterException.class)
+ @Test
public void testFailsToCreateLookupTranslatorThrowsInvalidParameterException() {
- new LookupTranslator(null);
+ assertThatExceptionOfType(InvalidParameterException.class).isThrownBy(() -> new LookupTranslator(null));
}
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/translate/NumericEntityEscaperTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/translate/NumericEntityEscaperTest.java b/src/test/java/org/apache/commons/text/translate/NumericEntityEscaperTest.java
index 160795a..121136a 100644
--- a/src/test/java/org/apache/commons/text/translate/NumericEntityEscaperTest.java
+++ b/src/test/java/org/apache/commons/text/translate/NumericEntityEscaperTest.java
@@ -17,7 +17,7 @@
package org.apache.commons.text.translate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/translate/NumericEntityUnescaperTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/translate/NumericEntityUnescaperTest.java b/src/test/java/org/apache/commons/text/translate/NumericEntityUnescaperTest.java
index 08665a2..341cd63 100644
--- a/src/test/java/org/apache/commons/text/translate/NumericEntityUnescaperTest.java
+++ b/src/test/java/org/apache/commons/text/translate/NumericEntityUnescaperTest.java
@@ -17,7 +17,7 @@
package org.apache.commons.text.translate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/translate/OctalUnescaperTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/translate/OctalUnescaperTest.java b/src/test/java/org/apache/commons/text/translate/OctalUnescaperTest.java
index 2d6efd3..8e4462f 100644
--- a/src/test/java/org/apache/commons/text/translate/OctalUnescaperTest.java
+++ b/src/test/java/org/apache/commons/text/translate/OctalUnescaperTest.java
@@ -17,7 +17,7 @@
package org.apache.commons.text.translate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/translate/SinglePassTranslatorTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/translate/SinglePassTranslatorTest.java b/src/test/java/org/apache/commons/text/translate/SinglePassTranslatorTest.java
index 081dc13..82b0ce2 100644
--- a/src/test/java/org/apache/commons/text/translate/SinglePassTranslatorTest.java
+++ b/src/test/java/org/apache/commons/text/translate/SinglePassTranslatorTest.java
@@ -16,14 +16,15 @@
*/
package org.apache.commons.text.translate;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Unit test for {@link SinglePassTranslator}
@@ -38,7 +39,7 @@ public class SinglePassTranslatorTest {
private StringWriter out;
- @Before
+ @BeforeEach
public void before() {
out = new StringWriter();
}
@@ -50,14 +51,14 @@ public class SinglePassTranslatorTest {
assertThat(dummyTranslator.translate("abcdefg", 0, out)).isEqualTo(7);
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void indexIsValidated() throws Exception {
- dummyTranslator.translate("abc", 1, out);
+ assertThatIllegalArgumentException().isThrownBy(() -> dummyTranslator.translate("abc", 1, out));
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testTranslateThrowsIllegalArgumentException() throws IOException {
- dummyTranslator.translate("(,Fk", 647, null);
+ assertThatIllegalArgumentException().isThrownBy(() -> dummyTranslator.translate("(,Fk", 647, null));
}
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/translate/UnicodeEscaperTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/translate/UnicodeEscaperTest.java b/src/test/java/org/apache/commons/text/translate/UnicodeEscaperTest.java
index c4026c9..8f4bfe1 100644
--- a/src/test/java/org/apache/commons/text/translate/UnicodeEscaperTest.java
+++ b/src/test/java/org/apache/commons/text/translate/UnicodeEscaperTest.java
@@ -17,7 +17,7 @@
package org.apache.commons.text.translate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/translate/UnicodeUnescaperTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/translate/UnicodeUnescaperTest.java b/src/test/java/org/apache/commons/text/translate/UnicodeUnescaperTest.java
index 472a21c..c209fa7 100644
--- a/src/test/java/org/apache/commons/text/translate/UnicodeUnescaperTest.java
+++ b/src/test/java/org/apache/commons/text/translate/UnicodeUnescaperTest.java
@@ -17,7 +17,7 @@
package org.apache.commons.text.translate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/translate/UnicodeUnpairedSurrogateRemoverTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/translate/UnicodeUnpairedSurrogateRemoverTest.java b/src/test/java/org/apache/commons/text/translate/UnicodeUnpairedSurrogateRemoverTest.java
index 7eacb57..3ba4a6d 100644
--- a/src/test/java/org/apache/commons/text/translate/UnicodeUnpairedSurrogateRemoverTest.java
+++ b/src/test/java/org/apache/commons/text/translate/UnicodeUnpairedSurrogateRemoverTest.java
@@ -16,7 +16,7 @@
*/
package org.apache.commons.text.translate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.CharArrayWriter;
import java.io.IOException;
[2/4] [text] Update tests from JUnit 4 to 5. Closes #79.
Posted by gg...@apache.org.
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/StringEscapeUtilsTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/StringEscapeUtilsTest.java b/src/test/java/org/apache/commons/text/StringEscapeUtilsTest.java
index 84eba94..5b127ab 100644
--- a/src/test/java/org/apache/commons/text/StringEscapeUtilsTest.java
+++ b/src/test/java/org/apache/commons/text/StringEscapeUtilsTest.java
@@ -16,7 +16,7 @@
*/
package org.apache.commons.text;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.StringWriter;
@@ -29,12 +29,12 @@ import java.nio.file.Paths;
import static org.apache.commons.text.StringEscapeUtils.escapeXSI;
import static org.apache.commons.text.StringEscapeUtils.unescapeXSI;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Unit tests for {@link StringEscapeUtils}.
@@ -62,35 +62,35 @@ public class StringEscapeUtilsTest {
assertNull(StringEscapeUtils.escapeJava(null));
try {
StringEscapeUtils.ESCAPE_JAVA.translate(null, null);
- fail();
+ fail("Exception expected!");
} catch (final IOException ex) {
- fail();
+ fail("Exception expected!");
} catch (final IllegalArgumentException ex) {
}
try {
StringEscapeUtils.ESCAPE_JAVA.translate("", null);
- fail();
+ fail("Exception expected!");
} catch (final IOException ex) {
- fail();
+ fail("Exception expected!");
} catch (final IllegalArgumentException ex) {
}
- assertEscapeJava("empty string", "", "");
+ assertEscapeJava("", "", "empty string");
assertEscapeJava(FOO, FOO);
- assertEscapeJava("tab", "\\t", "\t");
- assertEscapeJava("backslash", "\\\\", "\\");
- assertEscapeJava("single quote should not be escaped", "'", "'");
+ assertEscapeJava("\\t", "\t", "tab");
+ assertEscapeJava("\\\\", "\\", "backslash");
+ assertEscapeJava("'", "'", "single quote should not be escaped");
assertEscapeJava("\\\\\\b\\t\\r", "\\\b\t\r");
assertEscapeJava("\\u1234", "\u1234");
assertEscapeJava("\\u0234", "\u0234");
assertEscapeJava("\\u00EF", "\u00ef");
assertEscapeJava("\\u0001", "\u0001");
- assertEscapeJava("Should use capitalized Unicode hex", "\\uABCD", "\uabcd");
+ assertEscapeJava("\\uABCD", "\uabcd", "Should use capitalized Unicode hex");
assertEscapeJava("He didn't say, \\\"stop!\\\"",
"He didn't say, \"stop!\"");
- assertEscapeJava("non-breaking space", "This space is non-breaking:" + "\\u00A0",
- "This space is non-breaking:\u00a0");
+ assertEscapeJava("This space is non-breaking:" + "\\u00A0", "This space is non-breaking:\u00a0",
+ "non-breaking space");
assertEscapeJava("\\uABCD\\u1234\\u012C",
"\uABCD\u1234\u012C");
}
@@ -113,13 +113,13 @@ public class StringEscapeUtilsTest {
}
private void assertEscapeJava(final String escaped, final String original) throws IOException {
- assertEscapeJava(null, escaped, original);
+ assertEscapeJava(escaped, original, null);
}
- private void assertEscapeJava(String message, final String expected, final String original) throws IOException {
+ private void assertEscapeJava(final String expected, final String original, String message) throws IOException {
final String converted = StringEscapeUtils.escapeJava(original);
message = "escapeJava(String) failed" + (message == null ? "" : (": " + message));
- assertEquals(message, expected, converted);
+ assertEquals(expected, converted, message);
final StringWriter writer = new StringWriter();
StringEscapeUtils.ESCAPE_JAVA.translate(original, writer);
@@ -131,21 +131,21 @@ public class StringEscapeUtilsTest {
assertNull(StringEscapeUtils.unescapeJava(null));
try {
StringEscapeUtils.UNESCAPE_JAVA.translate(null, null);
- fail();
+ fail("Exception expected!");
} catch (final IOException ex) {
- fail();
+ fail("Exception expected!");
} catch (final IllegalArgumentException ex) {
}
try {
StringEscapeUtils.UNESCAPE_JAVA.translate("", null);
- fail();
+ fail("Exception expected!");
} catch (final IOException ex) {
- fail();
+ fail("Exception expected!");
} catch (final IllegalArgumentException ex) {
}
try {
StringEscapeUtils.unescapeJava("\\u02-3");
- fail();
+ fail("Exception expected!");
} catch (final RuntimeException ex) {
}
@@ -156,26 +156,25 @@ public class StringEscapeUtilsTest {
assertUnescapeJava("'\foo\teste\r", "\\'\\foo\\teste\\r");
assertUnescapeJava("", "\\");
//foo
- assertUnescapeJava("lowercase Unicode", "\uABCDx", "\\uabcdx");
- assertUnescapeJava("uppercase Unicode", "\uABCDx", "\\uABCDx");
- assertUnescapeJava("Unicode as final character", "\uABCD", "\\uabcd");
+ assertUnescapeJava("\uABCDx", "\\uabcdx", "lowercase Unicode");
+ assertUnescapeJava("\uABCDx", "\\uABCDx", "uppercase Unicode");
+ assertUnescapeJava("\uABCD", "\\uabcd", "Unicode as final character");
}
private void assertUnescapeJava(final String unescaped, final String original) throws IOException {
- assertUnescapeJava(null, unescaped, original);
+ assertUnescapeJava(unescaped, original, null);
}
- private void assertUnescapeJava(final String message, final String unescaped, final String original)
+ private void assertUnescapeJava(final String unescaped, final String original, final String message)
throws IOException {
final String expected = unescaped;
final String actual = StringEscapeUtils.unescapeJava(original);
- assertEquals("unescape(String) failed"
+ assertEquals(expected, actual, "unescape(String) failed"
+ (message == null ? "" : (": " + message))
+ ": expected '" + StringEscapeUtils.escapeJava(expected)
// we escape this so we can see it in the error message
- + "' actual '" + StringEscapeUtils.escapeJava(actual) + "'",
- expected, actual);
+ + "' actual '" + StringEscapeUtils.escapeJava(actual) + "'");
final StringWriter writer = new StringWriter();
StringEscapeUtils.UNESCAPE_JAVA.translate(original, writer);
@@ -187,16 +186,16 @@ public class StringEscapeUtilsTest {
assertNull(StringEscapeUtils.escapeEcmaScript(null));
try {
StringEscapeUtils.ESCAPE_ECMASCRIPT.translate(null, null);
- fail();
+ fail("Exception expected!");
} catch (final IOException ex) {
- fail();
+ fail("Exception expected!");
} catch (final IllegalArgumentException ex) {
}
try {
StringEscapeUtils.ESCAPE_ECMASCRIPT.translate("", null);
- fail();
+ fail("Exception expected!");
} catch (final IOException ex) {
- fail();
+ fail("Exception expected!");
} catch (final IllegalArgumentException ex) {
}
@@ -231,14 +230,14 @@ public class StringEscapeUtilsTest {
final String message = element[0];
final String expected = element[1];
final String original = element[2];
- assertEquals(message, expected, StringEscapeUtils.escapeHtml4(original));
+ assertEquals(expected, StringEscapeUtils.escapeHtml4(original), message);
final StringWriter sw = new StringWriter();
try {
StringEscapeUtils.ESCAPE_HTML3.translate(original, sw);
} catch (final IOException e) {
}
final String actual = original == null ? null : sw.toString();
- assertEquals(message, expected, actual);
+ assertEquals(expected, actual, message);
}
}
@@ -248,7 +247,7 @@ public class StringEscapeUtilsTest {
final String message = element[0];
final String expected = element[2];
final String original = element[1];
- assertEquals(message, expected, StringEscapeUtils.unescapeHtml3(original));
+ assertEquals(expected, StringEscapeUtils.unescapeHtml3(original), message);
final StringWriter sw = new StringWriter();
try {
@@ -256,12 +255,12 @@ public class StringEscapeUtilsTest {
} catch (final IOException e) {
}
final String actual = original == null ? null : sw.toString();
- assertEquals(message, expected, actual);
+ assertEquals(expected, actual, message);
}
// \u00E7 is a cedilla (c with wiggle under)
// note that the test string must be 7-bit-clean (Unicode escaped) or else it will compile incorrectly
// on some locales
- assertEquals("funny chars pass through OK", "Fran\u00E7ais", StringEscapeUtils.unescapeHtml3("Fran\u00E7ais"));
+ assertEquals("Fran\u00E7ais", StringEscapeUtils.unescapeHtml3("Fran\u00E7ais"), "funny chars pass through OK");
assertEquals("Hello&;World", StringEscapeUtils.unescapeHtml3("Hello&;World"));
assertEquals("Hello&#;World", StringEscapeUtils.unescapeHtml3("Hello&#;World"));
@@ -275,14 +274,14 @@ public class StringEscapeUtilsTest {
final String message = element[0];
final String expected = element[1];
final String original = element[2];
- assertEquals(message, expected, StringEscapeUtils.escapeHtml4(original));
+ assertEquals(expected, StringEscapeUtils.escapeHtml4(original), message);
final StringWriter sw = new StringWriter();
try {
StringEscapeUtils.ESCAPE_HTML4.translate(original, sw);
} catch (final IOException e) {
}
final String actual = original == null ? null : sw.toString();
- assertEquals(message, expected, actual);
+ assertEquals(expected, actual, message);
}
}
@@ -292,7 +291,7 @@ public class StringEscapeUtilsTest {
final String message = element[0];
final String expected = element[2];
final String original = element[1];
- assertEquals(message, expected, StringEscapeUtils.unescapeHtml4(original));
+ assertEquals(expected, StringEscapeUtils.unescapeHtml4(original), message);
final StringWriter sw = new StringWriter();
try {
@@ -300,12 +299,12 @@ public class StringEscapeUtilsTest {
} catch (final IOException e) {
}
final String actual = original == null ? null : sw.toString();
- assertEquals(message, expected, actual);
+ assertEquals(expected, actual, message);
}
// \u00E7 is a cedilla (c with wiggle under)
// note that the test string must be 7-bit-clean (Unicode escaped) or else it will compile incorrectly
// on some locales
- assertEquals("funny chars pass through OK", "Fran\u00E7ais", StringEscapeUtils.unescapeHtml4("Fran\u00E7ais"));
+ assertEquals("Fran\u00E7ais", StringEscapeUtils.unescapeHtml4("Fran\u00E7ais"), "funny chars pass through OK");
assertEquals("Hello&;World", StringEscapeUtils.unescapeHtml4("Hello&;World"));
assertEquals("Hello&#;World", StringEscapeUtils.unescapeHtml4("Hello&#;World"));
@@ -316,8 +315,8 @@ public class StringEscapeUtilsTest {
@Test
public void testUnescapeHexCharsHtml() {
// Simple easy to grok test
- assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml4("€Ÿ"));
- assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml4("€Ÿ"));
+ assertEquals("\u0080\u009F", StringEscapeUtils.unescapeHtml4("€Ÿ"), "hex number unescape");
+ assertEquals("\u0080\u009F", StringEscapeUtils.unescapeHtml4("€Ÿ"), "hex number unescape");
// Test all Character values:
for (char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) {
final Character c1 = i;
@@ -325,8 +324,8 @@ public class StringEscapeUtilsTest {
final String expected = c1.toString() + c2.toString();
final String escapedC1 = "&#x" + Integer.toHexString(c1) + ";";
final String escapedC2 = "&#x" + Integer.toHexString(c2) + ";";
- assertEquals("hex number unescape index " + i, expected,
- StringEscapeUtils.unescapeHtml4(escapedC1 + escapedC2));
+ assertEquals(expected, StringEscapeUtils.unescapeHtml4(escapedC1 + escapedC2),
+ "hex number unescape index " + i);
}
}
@@ -348,36 +347,36 @@ public class StringEscapeUtilsTest {
@Test
public void testEscapeXml10() {
assertEquals("a<b>c"d'e&f", StringEscapeUtils.escapeXml10("a<b>c\"d'e&f"));
- assertEquals("XML 1.0 should not escape \t \n \r",
- "a\tb\rc\nd", StringEscapeUtils.escapeXml10("a\tb\rc\nd"));
- assertEquals("XML 1.0 should omit most #x0-x8 | #xb | #xc | #xe-#x19",
- "ab", StringEscapeUtils.escapeXml10("a\u0000\u0001\u0008\u000b\u000c\u000e\u001fb"));
- assertEquals("XML 1.0 should omit #xd800-#xdfff",
- "a\ud7ff \ue000b", StringEscapeUtils.escapeXml10("a\ud7ff\ud800 \udfff \ue000b"));
- assertEquals("XML 1.0 should omit #xfffe | #xffff",
- "a\ufffdb", StringEscapeUtils.escapeXml10("a\ufffd\ufffe\uffffb"));
- assertEquals("XML 1.0 should escape #x7f-#x84 | #x86 - #x9f, for XML 1.1 compatibility",
- "a\u007e„\u0085†Ÿ\u00a0b",
- StringEscapeUtils.escapeXml10("a\u007e\u007f\u0084\u0085\u0086\u009f\u00a0b"));
+ assertEquals("a\tb\rc\nd", StringEscapeUtils.escapeXml10("a\tb\rc\nd"),
+ "XML 1.0 should not escape \t \n \r");
+ assertEquals("ab", StringEscapeUtils.escapeXml10("a\u0000\u0001\u0008\u000b\u000c\u000e\u001fb"),
+ "XML 1.0 should omit most #x0-x8 | #xb | #xc | #xe-#x19");
+ assertEquals("a\ud7ff \ue000b", StringEscapeUtils.escapeXml10("a\ud7ff\ud800 \udfff \ue000b"),
+ "XML 1.0 should omit #xd800-#xdfff");
+ assertEquals("a\ufffdb", StringEscapeUtils.escapeXml10("a\ufffd\ufffe\uffffb"),
+ "XML 1.0 should omit #xfffe | #xffff");
+ assertEquals("a\u007e„\u0085†Ÿ\u00a0b",
+ StringEscapeUtils.escapeXml10("a\u007e\u007f\u0084\u0085\u0086\u009f\u00a0b"),
+ "XML 1.0 should escape #x7f-#x84 | #x86 - #x9f, for XML 1.1 compatibility");
}
@Test
public void testEscapeXml11() {
assertEquals("a<b>c"d'e&f", StringEscapeUtils.escapeXml11("a<b>c\"d'e&f"));
- assertEquals("XML 1.1 should not escape \t \n \r",
- "a\tb\rc\nd", StringEscapeUtils.escapeXml11("a\tb\rc\nd"));
- assertEquals("XML 1.1 should omit #x0",
- "ab", StringEscapeUtils.escapeXml11("a\u0000b"));
- assertEquals("XML 1.1 should escape #x1-x8 | #xb | #xc | #xe-#x19",
- "ab",
- StringEscapeUtils.escapeXml11("a\u0001\u0008\u000b\u000c\u000e\u001fb"));
- assertEquals("XML 1.1 should escape #x7F-#x84 | #x86-#x9F",
- "a\u007e„\u0085†Ÿ\u00a0b",
- StringEscapeUtils.escapeXml11("a\u007e\u007f\u0084\u0085\u0086\u009f\u00a0b"));
- assertEquals("XML 1.1 should omit #xd800-#xdfff",
- "a\ud7ff \ue000b", StringEscapeUtils.escapeXml11("a\ud7ff\ud800 \udfff \ue000b"));
- assertEquals("XML 1.1 should omit #xfffe | #xffff",
- "a\ufffdb", StringEscapeUtils.escapeXml11("a\ufffd\ufffe\uffffb"));
+ assertEquals("a\tb\rc\nd", StringEscapeUtils.escapeXml11("a\tb\rc\nd"),
+ "XML 1.1 should not escape \t \n \r");
+ assertEquals("ab", StringEscapeUtils.escapeXml11("a\u0000b"),
+ "XML 1.1 should omit #x0");
+ assertEquals("ab",
+ StringEscapeUtils.escapeXml11("a\u0001\u0008\u000b\u000c\u000e\u001fb"),
+ "XML 1.1 should escape #x1-x8 | #xb | #xc | #xe-#x19");
+ assertEquals("a\u007e„\u0085†Ÿ\u00a0b",
+ StringEscapeUtils.escapeXml11("a\u007e\u007f\u0084\u0085\u0086\u009f\u00a0b"),
+ "XML 1.1 should escape #x7F-#x84 | #x86-#x9F");
+ assertEquals("a\ud7ff \ue000b", StringEscapeUtils.escapeXml11("a\ud7ff\ud800 \udfff \ue000b"),
+ "XML 1.1 should omit #xd800-#xdfff");
+ assertEquals("a\ufffdb", StringEscapeUtils.escapeXml11("a\ufffd\ufffe\uffffb"),
+ "XML 1.1 should omit #xfffe | #xffff");
}
/**
@@ -387,11 +386,11 @@ public class StringEscapeUtilsTest {
*/
@Test
public void testUnescapeXmlSupplementaryCharacters() {
- assertEquals("Supplementary character must be represented using a single escape", "\uD84C\uDFB4",
- StringEscapeUtils.unescapeXml("𣎴"));
+ assertEquals("\uD84C\uDFB4", StringEscapeUtils.unescapeXml("𣎴"),
+ "Supplementary character must be represented using a single escape");
- assertEquals("Supplementary characters mixed with basic characters should be decoded correctly",
- "a b c \uD84C\uDFB4", StringEscapeUtils.unescapeXml("a b c 𣎴"));
+ assertEquals("a b c \uD84C\uDFB4", StringEscapeUtils.unescapeXml("a b c 𣎴"),
+ "Supplementary characters mixed with basic characters should be decoded correctly");
}
// Tests issue #38569
@@ -495,10 +494,10 @@ public class StringEscapeUtilsTest {
final String original = new String(data, Charset.forName("UTF8"));
final String escaped = StringEscapeUtils.escapeHtml4(original);
- assertEquals("High Unicode should not have been escaped", original, escaped);
+ assertEquals(original, escaped, "High Unicode should not have been escaped");
final String unescaped = StringEscapeUtils.unescapeHtml4(escaped);
- assertEquals("High Unicode should have been unchanged", original, unescaped);
+ assertEquals(original, unescaped, "High Unicode should have been unchanged");
// TODO: I think this should hold, needs further investigation
// String unescapedFromEntity = StringEscapeUtils.unescapeHtml4("𝍢");
@@ -513,12 +512,12 @@ public class StringEscapeUtilsTest {
// Some random Japanese Unicode characters
final String original = "\u304B\u304C\u3068";
final String escaped = StringEscapeUtils.escapeHtml4(original);
- assertEquals("Hiragana character Unicode behaviour should not be being escaped by escapeHtml4",
- original, escaped);
+ assertEquals(original, escaped,
+ "Hiragana character Unicode behaviour should not be being escaped by escapeHtml4");
final String unescaped = StringEscapeUtils.unescapeHtml4(escaped);
- assertEquals("Hiragana character Unicode behaviour has changed - expected no unescaping", escaped, unescaped);
+ assertEquals(escaped, unescaped, "Hiragana character Unicode behaviour has changed - expected no unescaping");
}
/**
@@ -533,9 +532,9 @@ public class StringEscapeUtilsTest {
final String input = new String(inputBytes, StandardCharsets.UTF_8);
final String escaped = StringEscapeUtils.escapeEcmaScript(input);
// just the end:
- assertTrue(escaped, escaped.endsWith("}]"));
+ assertTrue(escaped.endsWith("}]"), escaped);
// a little more:
- assertTrue(escaped, escaped.endsWith("\"valueCode\\\":\\\"\\\"}]"));
+ assertTrue(escaped.endsWith("\"valueCode\\\":\\\"\\\"}]"), escaped);
}
/**
@@ -554,16 +553,16 @@ public class StringEscapeUtilsTest {
assertNull(StringEscapeUtils.escapeJson(null));
try {
StringEscapeUtils.ESCAPE_JSON.translate(null, null);
- fail();
+ fail("Exception expected!");
} catch (final IOException ex) {
- fail();
+ fail("Exception expected!");
} catch (final IllegalArgumentException ex) {
}
try {
StringEscapeUtils.ESCAPE_JSON.translate("", null);
- fail();
+ fail("Exception expected!");
} catch (final IOException ex) {
- fail();
+ fail("Exception expected!");
} catch (final IllegalArgumentException ex) {
}
@@ -601,7 +600,7 @@ public class StringEscapeUtilsTest {
@Test
public void testUnescapeEcmaScript() {
- assertNull("Should be null.", StringEscapeUtils.unescapeEcmaScript(null));
+ assertNull(StringEscapeUtils.unescapeEcmaScript(null));
assertEquals("8lvc1u+6B#-I", StringEscapeUtils.unescapeEcmaScript("8lvc1u+6B#-I"));
assertEquals("<script src=\"build/main.bundle.js\"></script>",
StringEscapeUtils.unescapeEcmaScript("<script src=\"build/main.bundle.js\"></script>"));
@@ -611,7 +610,7 @@ public class StringEscapeUtilsTest {
@Test
public void testEscapeHtmlThree() {
- assertNull("Should be null.", StringEscapeUtils.escapeHtml3(null));
+ assertNull(StringEscapeUtils.escapeHtml3(null));
assertEquals("a", StringEscapeUtils.escapeHtml3("a"));
assertEquals("<b>a", StringEscapeUtils.escapeHtml3("<b>a"));
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/StringSubstitutorTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/StringSubstitutorTest.java b/src/test/java/org/apache/commons/text/StringSubstitutorTest.java
index e389342..92ee70b 100644
--- a/src/test/java/org/apache/commons/text/StringSubstitutorTest.java
+++ b/src/test/java/org/apache/commons/text/StringSubstitutorTest.java
@@ -17,11 +17,12 @@
package org.apache.commons.text;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThatNullPointerException;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashMap;
import java.util.Map;
@@ -32,9 +33,9 @@ import org.apache.commons.text.lookup.StringLookup;
import org.apache.commons.text.lookup.StringLookupFactory;
import org.apache.commons.text.matcher.StringMatcher;
import org.apache.commons.text.matcher.StringMatcherFactory;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* Test class for {@link StringSubstitutor}.
@@ -147,14 +148,14 @@ public class StringSubstitutorTest {
}
}
- @Before
+ @BeforeEach
public void setUp() throws Exception {
values = new HashMap<>();
values.put("animal", "quick brown fox");
values.put("target", "lazy dog");
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
values = null;
}
@@ -311,12 +312,12 @@ public class StringSubstitutorTest {
values.put("species", "2");
final StringSubstitutor sub = new StringSubstitutor(values);
sub.setEnableSubstitutionInVariables(true);
- assertEquals("Wrong result (1)", "The mouse jumps over the lazy dog.",
+ assertEquals("The mouse jumps over the lazy dog.",
sub.replace("The ${animal.${species}} jumps over the ${target}."));
values.put("species", "1");
- assertEquals("Wrong result (2)", "The fox jumps over the lazy dog.",
+ assertEquals("The fox jumps over the lazy dog.",
sub.replace("The ${animal.${species}} jumps over the ${target}."));
- assertEquals("Wrong result (3)", "The fox jumps over the lazy dog.", sub.replace(
+ assertEquals("The fox jumps over the lazy dog.", sub.replace(
"The ${unknown.animal.${unknown.species:-1}:-fox} " + "jumps over the ${unknow.target:-lazy dog}."));
}
@@ -329,9 +330,9 @@ public class StringSubstitutorTest {
values.put("animal.2", "mouse");
values.put("species", "2");
final StringSubstitutor sub = new StringSubstitutor(values);
- assertEquals("Wrong result (1)", "The ${animal.${species}} jumps over the lazy dog.",
+ assertEquals("The ${animal.${species}} jumps over the lazy dog.",
sub.replace("The ${animal.${species}} jumps over the ${target}."));
- assertEquals("Wrong result (2)", "The ${animal.${species:-1}} jumps over the lazy dog.",
+ assertEquals("The ${animal.${species:-1}} jumps over the lazy dog.",
sub.replace("The ${animal.${species:-1}} jumps over the ${target}."));
}
@@ -347,9 +348,9 @@ public class StringSubstitutorTest {
values.put("species.brown", "2");
final StringSubstitutor sub = new StringSubstitutor(values);
sub.setEnableSubstitutionInVariables(true);
- assertEquals("Wrong result (1)", "The white mouse jumps over the lazy dog.",
+ assertEquals("The white mouse jumps over the lazy dog.",
sub.replace("The ${animal.${species.${color}}} jumps over the ${target}."));
- assertEquals("Wrong result (2)", "The brown fox jumps over the lazy dog.",
+ assertEquals("The brown fox jumps over the lazy dog.",
sub.replace("The ${animal.${species.${unknownColor:-brown}}} jumps over the ${target}."));
}
@@ -456,9 +457,9 @@ public class StringSubstitutorTest {
assertEquals('$', strSubstitutor.getEscapeChar());
}
- @Test(expected = NullPointerException.class)
+ @Test
public void testReplaceTakingThreeArgumentsThrowsNullPointerException() {
- StringSubstitutor.replace(null, (Properties) null);
+ assertThatNullPointerException().isThrownBy(() -> StringSubstitutor.replace(null, (Properties) null));
}
/**
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/StringSubstitutorWithInterpolatorStringLookupTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/StringSubstitutorWithInterpolatorStringLookupTest.java b/src/test/java/org/apache/commons/text/StringSubstitutorWithInterpolatorStringLookupTest.java
index bfac9c8..0eb1b3d 100644
--- a/src/test/java/org/apache/commons/text/StringSubstitutorWithInterpolatorStringLookupTest.java
+++ b/src/test/java/org/apache/commons/text/StringSubstitutorWithInterpolatorStringLookupTest.java
@@ -1,73 +1,73 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.commons.text;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.commons.text.lookup.StringLookupFactory;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class StringSubstitutorWithInterpolatorStringLookupTest {
-
- @Test
- public void testLocalHostLookup_Address() throws UnknownHostException {
- final StringSubstitutor strSubst = new StringSubstitutor(
- StringLookupFactory.INSTANCE.interpolatorStringLookup());
- Assert.assertEquals(InetAddress.getLocalHost().getHostAddress(), strSubst.replace("${localhost:address}"));
- }
-
- @Test
- public void testLocalHostLookup_CanonicalName() throws UnknownHostException {
- final StringSubstitutor strSubst = new StringSubstitutor(
- StringLookupFactory.INSTANCE.interpolatorStringLookup());
- Assert.assertEquals(InetAddress.getLocalHost().getCanonicalHostName(),
- strSubst.replace("${localhost:canonical-name}"));
- }
-
- @Test
- public void testLocalHostLookup_Name() throws UnknownHostException {
- final StringSubstitutor strSubst = new StringSubstitutor(
- StringLookupFactory.INSTANCE.interpolatorStringLookup());
- Assert.assertEquals(InetAddress.getLocalHost().getHostName(), strSubst.replace("${localhost:name}"));
- }
-
- @Test
- public void testMapAndSystemProperty() {
- final String key = "key";
- final String value = "value";
- final Map<String, String> map = new HashMap<>();
- map.put(key, value);
- final StringSubstitutor strSubst = new StringSubstitutor(
- StringLookupFactory.INSTANCE.interpolatorStringLookup(map));
- final String spKey = "user.name";
- Assert.assertEquals(System.getProperty(spKey), strSubst.replace("${sys:" + spKey + "}"));
- Assert.assertEquals(value, strSubst.replace("${" + key + "}"));
- }
-
- @Test
- public void testSystemProperty() {
- final StringSubstitutor strSubst = new StringSubstitutor(
- StringLookupFactory.INSTANCE.interpolatorStringLookup());
- final String spKey = "user.name";
- Assert.assertEquals(System.getProperty(spKey), strSubst.replace("${sys:" + spKey + "}"));
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.text;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.text.lookup.StringLookupFactory;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class StringSubstitutorWithInterpolatorStringLookupTest {
+
+ @Test
+ public void testLocalHostLookup_Address() throws UnknownHostException {
+ final StringSubstitutor strSubst = new StringSubstitutor(
+ StringLookupFactory.INSTANCE.interpolatorStringLookup());
+ Assertions.assertEquals(InetAddress.getLocalHost().getHostAddress(), strSubst.replace("${localhost:address}"));
+ }
+
+ @Test
+ public void testLocalHostLookup_CanonicalName() throws UnknownHostException {
+ final StringSubstitutor strSubst = new StringSubstitutor(
+ StringLookupFactory.INSTANCE.interpolatorStringLookup());
+ Assertions.assertEquals(InetAddress.getLocalHost().getCanonicalHostName(),
+ strSubst.replace("${localhost:canonical-name}"));
+ }
+
+ @Test
+ public void testLocalHostLookup_Name() throws UnknownHostException {
+ final StringSubstitutor strSubst = new StringSubstitutor(
+ StringLookupFactory.INSTANCE.interpolatorStringLookup());
+ Assertions.assertEquals(InetAddress.getLocalHost().getHostName(), strSubst.replace("${localhost:name}"));
+ }
+
+ @Test
+ public void testMapAndSystemProperty() {
+ final String key = "key";
+ final String value = "value";
+ final Map<String, String> map = new HashMap<>();
+ map.put(key, value);
+ final StringSubstitutor strSubst = new StringSubstitutor(
+ StringLookupFactory.INSTANCE.interpolatorStringLookup(map));
+ final String spKey = "user.name";
+ Assertions.assertEquals(System.getProperty(spKey), strSubst.replace("${sys:" + spKey + "}"));
+ Assertions.assertEquals(value, strSubst.replace("${" + key + "}"));
+ }
+
+ @Test
+ public void testSystemProperty() {
+ final StringSubstitutor strSubst = new StringSubstitutor(
+ StringLookupFactory.INSTANCE.interpolatorStringLookup());
+ final String spKey = "user.name";
+ Assertions.assertEquals(System.getProperty(spKey), strSubst.replace("${sys:" + spKey + "}"));
+ }
+}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/StringTokenizerTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/StringTokenizerTest.java b/src/test/java/org/apache/commons/text/StringTokenizerTest.java
index 397954a..d0ffd84 100644
--- a/src/test/java/org/apache/commons/text/StringTokenizerTest.java
+++ b/src/test/java/org/apache/commons/text/StringTokenizerTest.java
@@ -17,11 +17,11 @@
package org.apache.commons.text;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import java.util.Arrays;
import java.util.Collections;
@@ -30,7 +30,7 @@ import java.util.NoSuchElementException;
import org.apache.commons.text.matcher.StringMatcher;
import org.apache.commons.text.matcher.StringMatcherFactory;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Unit test for {@link StringTokenizer}.
@@ -60,10 +60,10 @@ public class StringTokenizerTest {
final String[] expected = {"a", "b", "c", "d;\"e", "f", "", "", "" };
- assertEquals(Arrays.toString(tokens), expected.length, tokens.length);
+ assertEquals(expected.length, tokens.length, Arrays.toString(tokens));
for (int i = 0; i < expected.length; i++) {
- assertEquals("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
- expected[i], tokens[i]);
+ assertEquals(expected[i], tokens[i],
+ "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'");
}
}
@@ -81,10 +81,10 @@ public class StringTokenizerTest {
final String[] expected = {"a", "b", "c ", "d;\"e", "f", " ", " ", "" };
- assertEquals(Arrays.toString(tokens), expected.length, tokens.length);
+ assertEquals(expected.length, tokens.length, Arrays.toString(tokens));
for (int i = 0; i < expected.length; i++) {
- assertEquals("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
- expected[i], tokens[i]);
+ assertEquals(expected[i], tokens[i],
+ "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'");
}
}
@@ -102,10 +102,10 @@ public class StringTokenizerTest {
final String[] expected = {"a", "b", " c", "d;\"e", "f", " ", " ", "" };
- assertEquals(Arrays.toString(tokens), expected.length, tokens.length);
+ assertEquals(expected.length, tokens.length, Arrays.toString(tokens));
for (int i = 0; i < expected.length; i++) {
- assertEquals("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
- expected[i], tokens[i]);
+ assertEquals(expected[i], tokens[i],
+ "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'");
}
}
@@ -123,10 +123,10 @@ public class StringTokenizerTest {
final String[] expected = {"a", "b", "c", "d;\"e", "f" };
- assertEquals(Arrays.toString(tokens), expected.length, tokens.length);
+ assertEquals(expected.length, tokens.length, Arrays.toString(tokens));
for (int i = 0; i < expected.length; i++) {
- assertEquals("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
- expected[i], tokens[i]);
+ assertEquals(expected[i], tokens[i],
+ "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'");
}
}
@@ -145,10 +145,10 @@ public class StringTokenizerTest {
final String[] expected = {"a", "b", "c", "d;\"e", "f", null, null, null };
- assertEquals(Arrays.toString(tokens), expected.length, tokens.length);
+ assertEquals(expected.length, tokens.length, Arrays.toString(tokens));
for (int i = 0; i < expected.length; i++) {
- assertEquals("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
- expected[i], tokens[i]);
+ assertEquals(expected[i], tokens[i],
+ "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'");
}
}
@@ -179,14 +179,11 @@ public class StringTokenizerTest {
prevCount++;
}
- assertEquals(Arrays.toString(tokens), expected.length, tokens.length);
-
- assertTrue("could not cycle through entire token list" + " using the 'hasNext' and 'next' methods",
- nextCount == expected.length);
-
- assertTrue("could not cycle through entire token list" + " using the 'hasPrevious' and 'previous' methods",
- prevCount == expected.length);
-
+ assertEquals(expected.length, tokens.length, Arrays.toString(tokens));
+ assertTrue(nextCount == expected.length,
+ "could not cycle through entire token list using the 'hasNext' and 'next' methods");
+ assertTrue(prevCount == expected.length,
+ "could not cycle through entire token list using the 'hasPrevious' and 'previous' methods");
}
@Test
@@ -202,10 +199,10 @@ public class StringTokenizerTest {
final String[] expected = {"a", "", "", "b", "c", "d e", "f", "" };
- assertEquals(Arrays.toString(tokens), expected.length, tokens.length);
+ assertEquals(expected.length, tokens.length, Arrays.toString(tokens));
for (int i = 0; i < expected.length; i++) {
- assertEquals("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
- expected[i], tokens[i]);
+ assertEquals(expected[i], tokens[i],
+ "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'");
}
}
@@ -223,10 +220,10 @@ public class StringTokenizerTest {
final String[] expected = {"a", "b", "c", "d e", "f" };
- assertEquals(Arrays.toString(tokens), expected.length, tokens.length);
+ assertEquals(expected.length, tokens.length, Arrays.toString(tokens));
for (int i = 0; i < expected.length; i++) {
- assertEquals("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
- expected[i], tokens[i]);
+ assertEquals(expected[i], tokens[i],
+ "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'");
}
}
@@ -578,7 +575,7 @@ public class StringTokenizerTest {
assertEquals(0, tokenizer.size());
try {
tokenizer.next();
- fail();
+ fail("Exception expected!");
} catch (final NoSuchElementException ex) {
}
}
@@ -844,7 +841,7 @@ public class StringTokenizerTest {
assertFalse(tkn.hasPrevious());
try {
tkn.previous();
- fail();
+ fail("Exception expected!");
} catch (final NoSuchElementException ex) {
}
assertTrue(tkn.hasNext());
@@ -852,17 +849,17 @@ public class StringTokenizerTest {
assertEquals("a", tkn.next());
try {
tkn.remove();
- fail();
+ fail("Exception expected!");
} catch (final UnsupportedOperationException ex) {
}
try {
tkn.set("x");
- fail();
+ fail("Exception expected!");
} catch (final UnsupportedOperationException ex) {
}
try {
tkn.add("y");
- fail();
+ fail("Exception expected!");
} catch (final UnsupportedOperationException ex) {
}
assertTrue(tkn.hasPrevious());
@@ -878,7 +875,7 @@ public class StringTokenizerTest {
try {
tkn.next();
- fail();
+ fail("Exception expected!");
} catch (final NoSuchElementException ex) {
}
assertTrue(tkn.hasPrevious());
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/TextStringBuilderAppendInsertTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/TextStringBuilderAppendInsertTest.java b/src/test/java/org/apache/commons/text/TextStringBuilderAppendInsertTest.java
index 8287d99..ce8d044 100644
--- a/src/test/java/org/apache/commons/text/TextStringBuilderAppendInsertTest.java
+++ b/src/test/java/org/apache/commons/text/TextStringBuilderAppendInsertTest.java
@@ -26,7 +26,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link TextStringBuilder}.
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/TextStringBuilderTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/TextStringBuilderTest.java b/src/test/java/org/apache/commons/text/TextStringBuilderTest.java
index 8a58f8d..7f713dc 100644
--- a/src/test/java/org/apache/commons/text/TextStringBuilderTest.java
+++ b/src/test/java/org/apache/commons/text/TextStringBuilderTest.java
@@ -17,14 +17,15 @@
package org.apache.commons.text;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.io.Reader;
@@ -38,7 +39,7 @@ import java.util.Arrays;
import org.apache.commons.text.matcher.StringMatcher;
import org.apache.commons.text.matcher.StringMatcherFactory;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link TextStringBuilder}.
@@ -481,13 +482,13 @@ public class TextStringBuilderTest {
assertEquals(0, sb.toCharArray().length);
char[] a = sb.toCharArray();
- assertNotNull("toCharArray() result is null", a);
- assertEquals("toCharArray() result is too large", 0, a.length);
+ assertNotNull(a, "toCharArray() result is null");
+ assertEquals(0, a.length, "toCharArray() result is too large");
sb.append("junit");
a = sb.toCharArray();
- assertEquals("toCharArray() result incorrect length", 5, a.length);
- assertTrue("toCharArray() result does not match", Arrays.equals("junit".toCharArray(), a));
+ assertEquals(5, a.length, "toCharArray() result incorrect length");
+ assertTrue(Arrays.equals("junit".toCharArray(), a), "toCharArray() result does not match");
}
@Test
@@ -497,19 +498,19 @@ public class TextStringBuilderTest {
sb.append("junit");
char[] a = sb.toCharArray(0, 20); // too large test
- assertEquals("toCharArray(int,int) result incorrect length", 5, a.length);
- assertTrue("toCharArray(int,int) result does not match", Arrays.equals("junit".toCharArray(), a));
+ assertEquals(5, a.length, "toCharArray(int,int) result incorrect length");
+ assertTrue(Arrays.equals("junit".toCharArray(), a), "toCharArray(int,int) result does not match");
a = sb.toCharArray(0, 4);
- assertEquals("toCharArray(int,int) result incorrect length", 4, a.length);
- assertTrue("toCharArray(int,int) result does not match", Arrays.equals("juni".toCharArray(), a));
+ assertEquals(4, a.length, "toCharArray(int,int) result incorrect length");
+ assertTrue(Arrays.equals("juni".toCharArray(), a), "toCharArray(int,int) result does not match");
a = sb.toCharArray(0, 4);
- assertEquals("toCharArray(int,int) result incorrect length", 4, a.length);
- assertTrue("toCharArray(int,int) result does not match", Arrays.equals("juni".toCharArray(), a));
+ assertEquals(4, a.length, "toCharArray(int,int) result incorrect length");
+ assertTrue(Arrays.equals("juni".toCharArray(), a), "toCharArray(int,int) result does not match");
a = sb.toCharArray(0, 1);
- assertNotNull("toCharArray(int,int) result is null", a);
+ assertNotNull(a, "toCharArray(int,int) result is null");
try {
sb.toCharArray(-1, 5);
@@ -1044,7 +1045,7 @@ public class TextStringBuilderTest {
sb = new TextStringBuilder("aaxaaaayaa");
try {
sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 11, sb.length(), -1);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException ex) {
}
assertEquals("aaxaaaayaa", sb.toString());
@@ -1052,7 +1053,7 @@ public class TextStringBuilderTest {
sb = new TextStringBuilder("aaxaaaayaa");
try {
sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", -1, sb.length(), -1);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException ex) {
}
assertEquals("aaxaaaayaa", sb.toString());
@@ -1107,7 +1108,7 @@ public class TextStringBuilderTest {
sb = new TextStringBuilder("aaxaaaayaa");
try {
sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 2, 1, -1);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException ex) {
}
assertEquals("aaxaaaayaa", sb.toString());
@@ -1215,28 +1216,28 @@ public class TextStringBuilderTest {
// Start index is negative
try {
sb.subSequence(-1, 5);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException e) {
}
// End index is negative
try {
sb.subSequence(2, -1);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException e) {
}
// End index greater than length()
try {
sb.subSequence(2, sb.length() + 1);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException e) {
}
// Start index greater then end index
try {
sb.subSequence(3, 2);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException e) {
}
@@ -1256,13 +1257,13 @@ public class TextStringBuilderTest {
assertEquals("hello goodbye".substring(0), sb.substring(0));
try {
sb.substring(-1);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException e) {
}
try {
sb.substring(15);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException e) {
}
@@ -1281,13 +1282,13 @@ public class TextStringBuilderTest {
try {
sb.substring(-1, 5);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException e) {
}
try {
sb.substring(15, 20);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException e) {
}
}
@@ -1764,27 +1765,27 @@ public class TextStringBuilderTest {
array = new char[3];
try {
reader.read(array, -1, 0);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException ex) {
}
try {
reader.read(array, 0, -1);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException ex) {
}
try {
reader.read(array, 100, 1);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException ex) {
}
try {
reader.read(array, 0, 100);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException ex) {
}
try {
reader.read(array, Integer.MAX_VALUE, Integer.MAX_VALUE);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException ex) {
}
@@ -1956,8 +1957,8 @@ public class TextStringBuilderTest {
public void testLang295() {
final TextStringBuilder sb = new TextStringBuilder("onetwothree");
sb.deleteFirst("three");
- assertFalse("The contains(char) method is looking beyond the end of the string", sb.contains('h'));
- assertEquals("The indexOf(char) method is looking beyond the end of the string", -1, sb.indexOf('h'));
+ assertFalse(sb.contains('h'), "The contains(char) method is looking beyond the end of the string");
+ assertEquals(-1, sb.indexOf('h'), "The indexOf(char) method is looking beyond the end of the string");
}
// -----------------------------------------------------------------------
@@ -1965,14 +1966,14 @@ public class TextStringBuilderTest {
public void testLang412Right() {
final TextStringBuilder sb = new TextStringBuilder();
sb.appendFixedWidthPadRight(null, 10, '*');
- assertEquals("Failed to invoke appendFixedWidthPadRight correctly", "**********", sb.toString());
+ assertEquals("**********", sb.toString(), "Failed to invoke appendFixedWidthPadRight correctly");
}
@Test
public void testLang412Left() {
final TextStringBuilder sb = new TextStringBuilder();
sb.appendFixedWidthPadLeft(null, 10, '*');
- assertEquals("Failed to invoke appendFixedWidthPadLeft correctly", "**********", sb.toString());
+ assertEquals("**********", sb.toString(), "Failed to invoke appendFixedWidthPadLeft correctly");
}
@Test
@@ -2121,27 +2122,33 @@ public class TextStringBuilderTest {
assertEquals("c" + System.lineSeparator(), sb1.appendln(ch).toString());
}
- @Test(expected = StringIndexOutOfBoundsException.class)
+ @Test
public void testAppendTakingTwoIntsWithZeroThrowsStringIndexOutOfBoundsException() {
- final Charset charset = Charset.defaultCharset();
- final ByteBuffer byteBuffer = charset.encode("end < start");
- final CharBuffer charBuffer = charset.decode(byteBuffer);
+ assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(() -> {
+ final Charset charset = Charset.defaultCharset();
+ final ByteBuffer byteBuffer = charset.encode("end < start");
+ final CharBuffer charBuffer = charset.decode(byteBuffer);
- new TextStringBuilder(630).append(charBuffer, 0, 630);
+ new TextStringBuilder(630).append(charBuffer, 0, 630);
+ });
}
- @Test(expected = StringIndexOutOfBoundsException.class)
+ @Test
public void testAppendTakingTwoIntsWithIndexOutOfBoundsThrowsStringIndexOutOfBoundsExceptionTwo() {
- final Charset charset = Charset.defaultCharset();
- final ByteBuffer byteBuffer = charset.encode("asdf");
- final CharBuffer charBuffer = charset.decode(byteBuffer);
+ assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(() -> {
+ final Charset charset = Charset.defaultCharset();
+ final ByteBuffer byteBuffer = charset.encode("asdf");
+ final CharBuffer charBuffer = charset.decode(byteBuffer);
- new TextStringBuilder().append(charBuffer, 933, 654);
+ new TextStringBuilder().append(charBuffer, 933, 654);
+ });
}
- @Test(expected = StringIndexOutOfBoundsException.class)
+ @Test
public void testDeleteCharAtWithNegative() {
- new TextStringBuilder().deleteCharAt((-1258));
+ assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(() -> {
+ new TextStringBuilder().deleteCharAt((-1258));
+ });
}
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/WordUtilsTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/WordUtilsTest.java b/src/test/java/org/apache/commons/text/WordUtilsTest.java
index 7ba224c..18d6eb9 100644
--- a/src/test/java/org/apache/commons/text/WordUtilsTest.java
+++ b/src/test/java/org/apache/commons/text/WordUtilsTest.java
@@ -17,12 +17,13 @@
package org.apache.commons.text;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import org.apache.commons.lang3.StringUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link WordUtils} class.
@@ -497,14 +498,18 @@ public class WordUtilsTest {
assertThat(WordUtils.abbreviate("01 23 45 67 89", 9, 10, "")).isEqualTo("01 23 45 6");
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testAbbreviateForLowerThanMinusOneValues() {
- assertThat(WordUtils.abbreviate("01 23 45 67 89", 9, -10, null)).isEqualTo("01 23 45 67");
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ assertThat(WordUtils.abbreviate("01 23 45 67 89", 9, -10, null)).isEqualTo("01 23 45 67");
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testAbbreviateUpperLessThanLowerValues() {
- assertThat(WordUtils.abbreviate("0123456789", 5, 2, "")).isEqualTo("01234");
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ assertThat(WordUtils.abbreviate("0123456789", 5, 2, "")).isEqualTo("01234");
+ });
}
@Test
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/diff/ReplacementsFinderTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/diff/ReplacementsFinderTest.java b/src/test/java/org/apache/commons/text/diff/ReplacementsFinderTest.java
index fddf406..27f6160 100644
--- a/src/test/java/org/apache/commons/text/diff/ReplacementsFinderTest.java
+++ b/src/test/java/org/apache/commons/text/diff/ReplacementsFinderTest.java
@@ -15,73 +15,57 @@
* limitations under the License.
*/
package org.apache.commons.text.diff;
-import static org.junit.Assert.assertArrayEquals;
+
import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+
import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
import java.util.List;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
/**
* Tests for the ReplacementsFinder.
*/
-@RunWith(Parameterized.class)
public class ReplacementsFinderTest {
+
private SimpleHandler handler = null;
- private final String left;
- private final String right;
- private final int skipped;
- private final Character[] from;
- private final Character[] to;
- @Before
+ @BeforeEach
public void setUp() {
handler = new SimpleHandler();
}
- @Parameters
- public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][] {
- {
+ public static Stream<Arguments> parameters() {
+ return Stream.of(
+ Arguments.of(
"branco",
"blanco",
1,
new Character[] {'r'},
- new Character[] {'l'}},
- {
+ new Character[] {'l'}),
+ Arguments.of(
"test the blocks before you use it",
"try the blocks before you put it",
25,
new Character[] {'e', 's', 't', 's', 'e'},
new Character[] {'r', 'y', 'p', 't'}
- }
- });
- }
-
- public ReplacementsFinderTest(final String left, final String right, final int skipped,
- final Character[] from, final Character[] to) {
- this.left = left;
- this.right = right;
- this.skipped = skipped;
- this.from = from;
- this.to = to;
+ ));
}
- @Test
- public void testReplacementsHandler() {
+ @ParameterizedTest
+ @MethodSource("parameters")
+ public void testReplacementsHandler(String left, String right, int skipped, Character[] from, Character[] to) {
final StringsComparator sc = new StringsComparator(left, right);
final ReplacementsFinder<Character> replacementFinder = new ReplacementsFinder<>(handler);
sc.getScript().visit(replacementFinder);
assertThat(handler.getSkipped()).as("Skipped characters do not match").isEqualTo(skipped);
- assertArrayEquals("From characters do not match", from,
- handler.getFrom().toArray(new Character[0]));
- assertArrayEquals("To characters do not match", to,
- handler.getTo().toArray(new Character[0]));
+ assertArrayEquals(handler.getFrom().toArray(new Character[0]), from, "From characters do not match");
+ assertArrayEquals(to, handler.getTo().toArray(new Character[0]), "To characters do not match");
}
// Helper RecplacementsHandler implementation for testing
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/diff/StringsComparatorTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/diff/StringsComparatorTest.java b/src/test/java/org/apache/commons/text/diff/StringsComparatorTest.java
index f731d16..9e9d266 100644
--- a/src/test/java/org/apache/commons/text/diff/StringsComparatorTest.java
+++ b/src/test/java/org/apache/commons/text/diff/StringsComparatorTest.java
@@ -18,9 +18,9 @@ package org.apache.commons.text.diff;
import java.util.Arrays;
import java.util.List;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -78,7 +78,7 @@ public class StringsComparatorTest {
return v.toString();
}
}
- @Before
+ @BeforeEach
public void setUp() {
before = Arrays.asList(
"bottle",
@@ -123,7 +123,7 @@ public class StringsComparatorTest {
2
};
}
- @After
+ @AfterEach
public void tearDown() {
before = null;
after = null;
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/lookup/DateStringLookupTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/lookup/DateStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/DateStringLookupTest.java
index 229a1e8..020baf3 100644
--- a/src/test/java/org/apache/commons/text/lookup/DateStringLookupTest.java
+++ b/src/test/java/org/apache/commons/text/lookup/DateStringLookupTest.java
@@ -1,50 +1,50 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache license, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the license for the specific language governing permissions and
- * limitations under the license.
- */
-
-package org.apache.commons.text.lookup;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-import org.junit.Test;
-
-public class DateStringLookupTest {
-
- @Test
- public void testDefault() throws ParseException {
- final String formatted = DateStringLookup.INSTANCE.lookup(null);
- DateFormat.getInstance().parse(formatted); // throws ParseException
-
- }
-
- @Test
- public void testFormat() {
- final String fomat = "yyyy-MM-dd";
- final String value = DateStringLookup.INSTANCE.lookup(fomat);
- assertNotNull("No Date", value);
- final SimpleDateFormat format = new SimpleDateFormat(fomat);
- final String today = format.format(new Date());
- assertEquals(value, today);
-
- }
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+
+package org.apache.commons.text.lookup;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import org.junit.jupiter.api.Test;
+
+public class DateStringLookupTest {
+
+ @Test
+ public void testDefault() throws ParseException {
+ final String formatted = DateStringLookup.INSTANCE.lookup(null);
+ DateFormat.getInstance().parse(formatted); // throws ParseException
+
+ }
+
+ @Test
+ public void testFormat() {
+ final String fomat = "yyyy-MM-dd";
+ final String value = DateStringLookup.INSTANCE.lookup(fomat);
+ assertNotNull("No Date", value);
+ final SimpleDateFormat format = new SimpleDateFormat(fomat);
+ final String today = format.format(new Date());
+ assertEquals(value, today);
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/lookup/EnvironmentVariableStringLookupTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/lookup/EnvironmentVariableStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/EnvironmentVariableStringLookupTest.java
index 643e3d7..1348e00 100644
--- a/src/test/java/org/apache/commons/text/lookup/EnvironmentVariableStringLookupTest.java
+++ b/src/test/java/org/apache/commons/text/lookup/EnvironmentVariableStringLookupTest.java
@@ -1,37 +1,37 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache license, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the license for the specific language governing permissions and
- * limitations under the license.
- */
-
-package org.apache.commons.text.lookup;
-
-import org.apache.commons.lang3.SystemUtils;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class EnvironmentVariableStringLookupTest {
-
- @Test
- public void testOne() {
- if (SystemUtils.IS_OS_WINDOWS) {
- final String key = "PATH";
- Assert.assertEquals(System.getenv(key), EnvironmentVariableStringLookup.INSTANCE.lookup(key));
- } else if (SystemUtils.IS_OS_LINUX) {
- final String key = "USER";
- Assert.assertEquals(System.getenv(key), EnvironmentVariableStringLookup.INSTANCE.lookup(key));
- }
- }
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+
+package org.apache.commons.text.lookup;
+
+import org.apache.commons.lang3.SystemUtils;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class EnvironmentVariableStringLookupTest {
+
+ @Test
+ public void testOne() {
+ if (SystemUtils.IS_OS_WINDOWS) {
+ final String key = "PATH";
+ Assertions.assertEquals(System.getenv(key), EnvironmentVariableStringLookup.INSTANCE.lookup(key));
+ } else if (SystemUtils.IS_OS_LINUX) {
+ final String key = "USER";
+ Assertions.assertEquals(System.getenv(key), EnvironmentVariableStringLookup.INSTANCE.lookup(key));
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/lookup/InterpolatorStringLookupTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/lookup/InterpolatorStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/InterpolatorStringLookupTest.java
index 0a86d9c..595d20c 100644
--- a/src/test/java/org/apache/commons/text/lookup/InterpolatorStringLookupTest.java
+++ b/src/test/java/org/apache/commons/text/lookup/InterpolatorStringLookupTest.java
@@ -1,101 +1,95 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache license, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the license for the specific language governing permissions and
- * limitations under the license.
- */
-package org.apache.commons.text.lookup;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.junit.rules.ExternalResource;
-import org.junit.rules.RuleChain;
-
-/**
- *
- */
-public class InterpolatorStringLookupTest {
-
- @ClassRule
- public static RuleChain rules = RuleChain.outerRule(new ExternalResource() {
- @Override
- protected void after() {
- System.clearProperty(TESTKEY);
- System.clearProperty(TESTKEY2);
- }
-
- @Override
- protected void before() throws Throwable {
- System.setProperty(TESTKEY, TESTVAL);
- System.setProperty(TESTKEY2, TESTVAL);
- }
- });
- private static final String TESTKEY = "TestKey";
- private static final String TESTKEY2 = "TestKey2";
-
- private static final String TESTVAL = "TestValue";
-
- private void assertLookupNotEmpty(final StringLookup lookup, final String key) {
- final String value = lookup.lookup(key);
- assertNotNull(value);
- assertFalse(value.isEmpty());
- System.out.println(key + " = " + value);
- }
-
- @Test
- public void testLookup() {
- final Map<String, String> map = new HashMap<>();
- map.put(TESTKEY, TESTVAL);
- final StringLookup lookup = new InterpolatorStringLookup(MapStringLookup.on(map));
- String value = lookup.lookup(TESTKEY);
- assertEquals(TESTVAL, value);
- value = lookup.lookup("ctx:" + TESTKEY);
- assertEquals(TESTVAL, value);
- value = lookup.lookup("sys:" + TESTKEY);
- assertEquals(TESTVAL, value);
- value = lookup.lookup("BadKey");
- assertNull(value);
- value = lookup.lookup("ctx:" + TESTKEY);
- assertEquals(TESTVAL, value);
- }
-
- @Test
- public void testLookupWithDefaultInterpolator() {
- final StringLookup lookup = new InterpolatorStringLookup();
- String value = lookup.lookup("sys:" + TESTKEY);
- assertEquals(TESTVAL, value);
- value = lookup.lookup("env:PATH");
- assertNotNull(value);
- value = lookup.lookup("date:yyyy-MM-dd");
- assertNotNull("No Date", value);
- final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
- final String today = format.format(new Date());
- assertEquals(value, today);
- assertLookupNotEmpty(lookup, "java:version");
- assertLookupNotEmpty(lookup, "java:runtime");
- assertLookupNotEmpty(lookup, "java:vm");
- assertLookupNotEmpty(lookup, "java:os");
- assertLookupNotEmpty(lookup, "java:locale");
- assertLookupNotEmpty(lookup, "java:hardware");
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.commons.text.lookup;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+public class InterpolatorStringLookupTest {
+
+ @BeforeAll
+ public static void beforeAll() throws Throwable {
+ System.setProperty(TESTKEY, TESTVAL);
+ System.setProperty(TESTKEY2, TESTVAL);
+ }
+
+ @AfterAll
+ public static void afterAll() throws Throwable {
+ System.clearProperty(TESTKEY);
+ System.clearProperty(TESTKEY2);
+ }
+
+ private static final String TESTKEY = "TestKey";
+ private static final String TESTKEY2 = "TestKey2";
+
+ private static final String TESTVAL = "TestValue";
+
+ private void assertLookupNotEmpty(final StringLookup lookup, final String key) {
+ final String value = lookup.lookup(key);
+ assertNotNull(value);
+ assertFalse(value.isEmpty());
+ System.out.println(key + " = " + value);
+ }
+
+ @Test
+ public void testLookup() {
+ final Map<String, String> map = new HashMap<>();
+ map.put(TESTKEY, TESTVAL);
+ final StringLookup lookup = new InterpolatorStringLookup(MapStringLookup.on(map));
+ String value = lookup.lookup(TESTKEY);
+ assertEquals(TESTVAL, value);
+ value = lookup.lookup("ctx:" + TESTKEY);
+ assertEquals(TESTVAL, value);
+ value = lookup.lookup("sys:" + TESTKEY);
+ assertEquals(TESTVAL, value);
+ value = lookup.lookup("BadKey");
+ assertNull(value);
+ value = lookup.lookup("ctx:" + TESTKEY);
+ assertEquals(TESTVAL, value);
+ }
+
+ @Test
+ public void testLookupWithDefaultInterpolator() {
+ final StringLookup lookup = new InterpolatorStringLookup();
+ String value = lookup.lookup("sys:" + TESTKEY);
+ assertEquals(TESTVAL, value);
+ value = lookup.lookup("env:PATH");
+ assertNotNull(value);
+ value = lookup.lookup("date:yyyy-MM-dd");
+ assertNotNull("No Date", value);
+ final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
+ final String today = format.format(new Date());
+ assertEquals(value, today);
+ assertLookupNotEmpty(lookup, "java:version");
+ assertLookupNotEmpty(lookup, "java:runtime");
+ assertLookupNotEmpty(lookup, "java:vm");
+ assertLookupNotEmpty(lookup, "java:os");
+ assertLookupNotEmpty(lookup, "java:locale");
+ assertLookupNotEmpty(lookup, "java:hardware");
+ }
+}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/lookup/JavaPlatformStringLookupTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/lookup/JavaPlatformStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/JavaPlatformStringLookupTest.java
index 9a8941b..c7dd110 100644
--- a/src/test/java/org/apache/commons/text/lookup/JavaPlatformStringLookupTest.java
+++ b/src/test/java/org/apache/commons/text/lookup/JavaPlatformStringLookupTest.java
@@ -1,31 +1,32 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache license, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the license for the specific language governing permissions and
- * limitations under the license.
- */
-
-package org.apache.commons.text.lookup;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-public class JavaPlatformStringLookupTest {
-
- @Test
- public void testVm() {
- final String key = "vm";
- Assert.assertTrue(JavaPlatformStringLookup.INSTANCE.lookup(key).contains(System.getProperty("java.vm.name")));
- }
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+
+package org.apache.commons.text.lookup;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.Test;
+
+public class JavaPlatformStringLookupTest {
+
+ @Test
+ public void testVm() {
+ final String key = "vm";
+ assertTrue(JavaPlatformStringLookup.INSTANCE.lookup(key).contains(System.getProperty("java.vm.name")));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/lookup/LocalHostStringLookupTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/lookup/LocalHostStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/LocalHostStringLookupTest.java
index c00a7dc..1ca1487 100644
--- a/src/test/java/org/apache/commons/text/lookup/LocalHostStringLookupTest.java
+++ b/src/test/java/org/apache/commons/text/lookup/LocalHostStringLookupTest.java
@@ -1,46 +1,46 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache license, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the license for the specific language governing permissions and
- * limitations under the license.
- */
-
-package org.apache.commons.text.lookup;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-public class LocalHostStringLookupTest {
-
- @Test
- public void testAddress() throws UnknownHostException {
- Assert.assertEquals(InetAddress.getLocalHost().getHostAddress(),
- LocalHostStringLookup.INSTANCE.lookup("address"));
- }
-
- @Test
- public void testCanonicalName() throws UnknownHostException {
- Assert.assertEquals(InetAddress.getLocalHost().getCanonicalHostName(),
- LocalHostStringLookup.INSTANCE.lookup("canonical-name"));
- }
-
- @Test
- public void testName() throws UnknownHostException {
- Assert.assertEquals(InetAddress.getLocalHost().getHostName(),
- LocalHostStringLookup.INSTANCE.lookup("name"));
- }
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+
+package org.apache.commons.text.lookup;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class LocalHostStringLookupTest {
+
+ @Test
+ public void testAddress() throws UnknownHostException {
+ Assertions.assertEquals(InetAddress.getLocalHost().getHostAddress(),
+ LocalHostStringLookup.INSTANCE.lookup("address"));
+ }
+
+ @Test
+ public void testCanonicalName() throws UnknownHostException {
+ Assertions.assertEquals(InetAddress.getLocalHost().getCanonicalHostName(),
+ LocalHostStringLookup.INSTANCE.lookup("canonical-name"));
+ }
+
+ @Test
+ public void testName() throws UnknownHostException {
+ Assertions.assertEquals(InetAddress.getLocalHost().getHostName(),
+ LocalHostStringLookup.INSTANCE.lookup("name"));
+ }
+
+}
[3/4] [text] Update tests from JUnit 4 to 5. Closes #79.
Posted by gg...@apache.org.
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/StrSubstitutorTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/StrSubstitutorTest.java b/src/test/java/org/apache/commons/text/StrSubstitutorTest.java
index 04f95bb..dcd6297 100644
--- a/src/test/java/org/apache/commons/text/StrSubstitutorTest.java
+++ b/src/test/java/org/apache/commons/text/StrSubstitutorTest.java
@@ -1,835 +1,829 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.commons.text;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-import org.apache.commons.lang3.mutable.MutableObject;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * Test class for {@link StrSubstitutor}.
- *
- * @deprecated This class will be removed in 2.0.
- */
-@Deprecated
-public class StrSubstitutorTest {
-
- private Map<String, String> values;
-
- @Before
- public void setUp() throws Exception {
- values = new HashMap<>();
- values.put("animal", "quick brown fox");
- values.put("target", "lazy dog");
- }
-
- @After
- public void tearDown() throws Exception {
- values = null;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Tests simple key replace.
- */
- @Test
- public void testReplaceSimple() {
- doTestReplace("The quick brown fox jumps over the lazy dog.", "The ${animal} jumps over the ${target}.", true);
- }
-
- /**
- * Tests simple key replace.
- */
- @Test
- public void testReplaceSolo() {
- doTestReplace("quick brown fox", "${animal}", false);
- }
-
- /**
- * Tests replace with no variables.
- */
- @Test
- public void testReplaceNoVariables() {
- doTestNoReplace("The balloon arrived.");
- }
-
- /**
- * Tests replace with null.
- */
- @Test
- public void testReplaceNull() {
- doTestNoReplace(null);
- }
-
- /**
- * Tests replace with null.
- */
- @Test
- public void testReplaceEmpty() {
- doTestNoReplace("");
- }
-
- /**
- * Tests key replace changing map after initialization (not recommended).
- */
- @Test
- public void testReplaceChangedMap() {
- final StrSubstitutor sub = new StrSubstitutor(values);
- values.put("target", "moon");
- assertEquals("The quick brown fox jumps over the moon.",
- sub.replace("The ${animal} jumps over the ${target}."));
- }
-
- /**
- * Tests unknown key replace.
- */
- @Test
- public void testReplaceUnknownKey() {
- doTestReplace("The ${person} jumps over the lazy dog.", "The ${person} jumps over the ${target}.", true);
- doTestReplace("The ${person} jumps over the lazy dog. 1234567890.",
- "The ${person} jumps over the ${target}. ${undefined.number:-1234567890}.", true);
- }
-
- /**
- * Tests adjacent keys.
- */
- @Test
- public void testReplaceAdjacentAtStart() {
- values.put("code", "GBP");
- values.put("amount", "12.50");
- final StrSubstitutor sub = new StrSubstitutor(values);
- assertEquals("GBP12.50 charged", sub.replace("${code}${amount} charged"));
- }
-
- /**
- * Tests adjacent keys.
- */
- @Test
- public void testReplaceAdjacentAtEnd() {
- values.put("code", "GBP");
- values.put("amount", "12.50");
- final StrSubstitutor sub = new StrSubstitutor(values);
- assertEquals("Amount is GBP12.50", sub.replace("Amount is ${code}${amount}"));
- }
-
- /**
- * Tests simple recursive replace.
- */
- @Test
- public void testReplaceRecursive() {
- values.put("animal", "${critter}");
- values.put("target", "${pet}");
- values.put("pet", "${petCharacteristic} dog");
- values.put("petCharacteristic", "lazy");
- values.put("critter", "${critterSpeed} ${critterColor} ${critterType}");
- values.put("critterSpeed", "quick");
- values.put("critterColor", "brown");
- values.put("critterType", "fox");
- doTestReplace("The quick brown fox jumps over the lazy dog.", "The ${animal} jumps over the ${target}.", true);
-
- values.put("pet", "${petCharacteristicUnknown:-lazy} dog");
- doTestReplace("The quick brown fox jumps over the lazy dog.", "The ${animal} jumps over the ${target}.", true);
- }
-
- @Test
- public void testDisableSubstitutionInValues() {
- final StrSubstitutor sub = new StrSubstitutor(values);
- sub.setDisableSubstitutionInValues(true);
- values.put("animal", "${critter}");
- values.put("target", "${pet}");
- values.put("pet", "${petCharacteristic} dog");
- values.put("petCharacteristic", "lazy");
- values.put("critter", "${critterSpeed} ${critterColor} ${critterType}");
- values.put("critterSpeed", "quick");
- values.put("critterColor", "brown");
- values.put("critterType", "fox");
- doTestReplace(sub, "The ${critter} jumps over the ${pet}.", "The ${animal} jumps over the ${target}.", true);
- }
-
- /**
- * Tests escaping.
- */
- @Test
- public void testReplaceEscaping() {
- doTestReplace("The ${animal} jumps over the lazy dog.", "The $${animal} jumps over the ${target}.", true);
- }
-
- /**
- * Tests escaping.
- */
- @Test
- public void testReplaceSoloEscaping() {
- doTestReplace("${animal}", "$${animal}", false);
- }
-
- /**
- * Tests complex escaping.
- */
- @Test
- public void testReplaceComplexEscaping() {
- doTestReplace("The ${quick brown fox} jumps over the lazy dog.",
- "The $${${animal}} jumps over the ${target}.", true);
- doTestReplace("The ${quick brown fox} jumps over the lazy dog. ${1234567890}.",
- "The $${${animal}} jumps over the ${target}. $${${undefined.number:-1234567890}}.", true);
- }
-
- /**
- * Tests when no prefix or suffix.
- */
- @Test
- public void testReplaceNoPrefixNoSuffix() {
- doTestReplace("The animal jumps over the lazy dog.", "The animal jumps over the ${target}.", true);
- }
-
- /**
- * Tests when no incomplete prefix.
- */
- @Test
- public void testReplaceIncompletePrefix() {
- doTestReplace("The {animal} jumps over the lazy dog.", "The {animal} jumps over the ${target}.", true);
- }
-
- /**
- * Tests when prefix but no suffix.
- */
- @Test
- public void testReplacePrefixNoSuffix() {
- doTestReplace("The ${animal jumps over the ${target} lazy dog.",
- "The ${animal jumps over the ${target} ${target}.", true);
- }
-
- /**
- * Tests when suffix but no prefix.
- */
- @Test
- public void testReplaceNoPrefixSuffix() {
- doTestReplace("The animal} jumps over the lazy dog.", "The animal} jumps over the ${target}.", true);
- }
-
- /**
- * Tests when no variable name.
- */
- @Test
- public void testReplaceEmptyKeys() {
- doTestReplace("The ${} jumps over the lazy dog.", "The ${} jumps over the ${target}.", true);
- doTestReplace("The animal jumps over the lazy dog.", "The ${:-animal} jumps over the ${target}.", true);
- }
-
- /**
- * Tests replace creates output same as input.
- */
- @Test
- public void testReplaceToIdentical() {
- values.put("animal", "$${${thing}}");
- values.put("thing", "animal");
- doTestReplace("The ${animal} jumps.", "The ${animal} jumps.", true);
- }
-
- /**
- * Tests a cyclic replace operation.
- * The cycle should be detected and cause an exception to be thrown.
- */
- @Test
- public void testCyclicReplacement() {
- final Map<String, String> map = new HashMap<>();
- map.put("animal", "${critter}");
- map.put("target", "${pet}");
- map.put("pet", "${petCharacteristic} dog");
- map.put("petCharacteristic", "lazy");
- map.put("critter", "${critterSpeed} ${critterColor} ${critterType}");
- map.put("critterSpeed", "quick");
- map.put("critterColor", "brown");
- map.put("critterType", "${animal}");
- StrSubstitutor sub = new StrSubstitutor(map);
- try {
- sub.replace("The ${animal} jumps over the ${target}.");
- fail("Cyclic replacement was not detected!");
- } catch (final IllegalStateException ex) {
- // expected
- }
-
- // also check even when default value is set.
- map.put("critterType", "${animal:-fox}");
- sub = new StrSubstitutor(map);
- try {
- sub.replace("The ${animal} jumps over the ${target}.");
- fail("Cyclic replacement was not detected!");
- } catch (final IllegalStateException ex) {
- // expected
- }
- }
-
- /**
- * Tests interpolation with weird boundary patterns.
- */
- @Test
- public void testReplaceWeirdPattens() {
- doTestNoReplace("");
- doTestNoReplace("${}");
- doTestNoReplace("${ }");
- doTestNoReplace("${\t}");
- doTestNoReplace("${\n}");
- doTestNoReplace("${\b}");
- doTestNoReplace("${");
- doTestNoReplace("$}");
- doTestNoReplace("}");
- doTestNoReplace("${}$");
- doTestNoReplace("${${");
- doTestNoReplace("${${}}");
- doTestNoReplace("${$${}}");
- doTestNoReplace("${$$${}}");
- doTestNoReplace("${$$${$}}");
- doTestNoReplace("${${}}");
- doTestNoReplace("${${ }}");
- }
-
- /**
- * Tests simple key replace.
- */
- @Test
- public void testReplacePartialString_noReplace() {
- final StrSubstitutor sub = new StrSubstitutor();
- assertEquals("${animal} jumps", sub.replace("The ${animal} jumps over the ${target}.", 4, 15));
- }
-
- /**
- * Tests whether a variable can be replaced in a variable name.
- */
- @Test
- public void testReplaceInVariable() {
- values.put("animal.1", "fox");
- values.put("animal.2", "mouse");
- values.put("species", "2");
- final StrSubstitutor sub = new StrSubstitutor(values);
- sub.setEnableSubstitutionInVariables(true);
- assertEquals(
- "Wrong result (1)",
- "The mouse jumps over the lazy dog.",
- sub.replace("The ${animal.${species}} jumps over the ${target}."));
- values.put("species", "1");
- assertEquals(
- "Wrong result (2)",
- "The fox jumps over the lazy dog.",
- sub.replace("The ${animal.${species}} jumps over the ${target}."));
- assertEquals(
- "Wrong result (3)",
- "The fox jumps over the lazy dog.",
- sub.replace("The ${unknown.animal.${unknown.species:-1}:-fox} "
- + "jumps over the ${unknow.target:-lazy dog}."));
- }
-
- /**
- * Tests whether substitution in variable names is disabled per default.
- */
- @Test
- public void testReplaceInVariableDisabled() {
- values.put("animal.1", "fox");
- values.put("animal.2", "mouse");
- values.put("species", "2");
- final StrSubstitutor sub = new StrSubstitutor(values);
- assertEquals(
- "Wrong result (1)",
- "The ${animal.${species}} jumps over the lazy dog.",
- sub.replace("The ${animal.${species}} jumps over the ${target}."));
- assertEquals(
- "Wrong result (2)",
- "The ${animal.${species:-1}} jumps over the lazy dog.",
- sub.replace("The ${animal.${species:-1}} jumps over the ${target}."));
- }
-
- /**
- * Tests complex and recursive substitution in variable names.
- */
- @Test
- public void testReplaceInVariableRecursive() {
- values.put("animal.2", "brown fox");
- values.put("animal.1", "white mouse");
- values.put("color", "white");
- values.put("species.white", "1");
- values.put("species.brown", "2");
- final StrSubstitutor sub = new StrSubstitutor(values);
- sub.setEnableSubstitutionInVariables(true);
- assertEquals(
- "Wrong result (1)",
- "The white mouse jumps over the lazy dog.",
- sub.replace("The ${animal.${species.${color}}} jumps over the ${target}."));
- assertEquals(
- "Wrong result (2)",
- "The brown fox jumps over the lazy dog.",
- sub.replace("The ${animal.${species.${unknownColor:-brown}}} jumps over the ${target}."));
- }
-
- @Test
- public void testDefaultValueDelimiters() {
- final Map<String, String> map = new HashMap<>();
- map.put("animal", "fox");
- map.put("target", "dog");
-
- StrSubstitutor sub = new StrSubstitutor(map, "${", "}", '$');
- assertEquals("The fox jumps over the lazy dog. 1234567890.",
- sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number:-1234567890}."));
-
- sub = new StrSubstitutor(map, "${", "}", '$', "?:");
- assertEquals("The fox jumps over the lazy dog. 1234567890.",
- sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number?:1234567890}."));
-
- sub = new StrSubstitutor(map, "${", "}", '$', "||");
- assertEquals("The fox jumps over the lazy dog. 1234567890.",
- sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number||1234567890}."));
-
- sub = new StrSubstitutor(map, "${", "}", '$', "!");
- assertEquals("The fox jumps over the lazy dog. 1234567890.",
- sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number!1234567890}."));
-
- sub = new StrSubstitutor(map, "${", "}", '$', "");
- sub.setValueDelimiterMatcher(null);
- assertEquals("The fox jumps over the lazy dog. ${undefined.number!1234567890}.",
- sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number!1234567890}."));
-
- sub = new StrSubstitutor(map, "${", "}", '$');
- sub.setValueDelimiterMatcher(null);
- assertEquals("The fox jumps over the lazy dog. ${undefined.number!1234567890}.",
- sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number!1234567890}."));
- }
-
- //-----------------------------------------------------------------------
- /**
- * Tests protected.
- */
- @Test
- public void testResolveVariable() {
- final StrBuilder builder = new StrBuilder("Hi ${name}!");
- final Map<String, String> map = new HashMap<>();
- map.put("name", "commons");
- final StrSubstitutor sub = new StrSubstitutor(map) {
- @Override
- protected String resolveVariable(final String variableName, final StrBuilder buf, final int startPos,
- final int endPos) {
- assertEquals("name", variableName);
- assertSame(builder, buf);
- assertEquals(3, startPos);
- assertEquals(10, endPos);
- return "jakarta";
- }
- };
- sub.replaceIn(builder);
- assertEquals("Hi jakarta!", builder.toString());
- }
-
- //-----------------------------------------------------------------------
- /**
- * Tests constructor.
- */
- @Test
- public void testConstructorNoArgs() {
- final StrSubstitutor sub = new StrSubstitutor();
- assertEquals("Hi ${name}", sub.replace("Hi ${name}"));
- }
-
- /**
- * Tests constructor.
- */
- @Test
- public void testConstructorMapPrefixSuffix() {
- final Map<String, String> map = new HashMap<>();
- map.put("name", "commons");
- final StrSubstitutor sub = new StrSubstitutor(map, "<", ">");
- assertEquals("Hi < commons", sub.replace("Hi $< <name>"));
- }
-
- /**
- * Tests constructor.
- */
- @Test
- public void testConstructorMapFull() {
- final Map<String, String> map = new HashMap<>();
- map.put("name", "commons");
- StrSubstitutor sub = new StrSubstitutor(map, "<", ">", '!');
- assertEquals("Hi < commons", sub.replace("Hi !< <name>"));
- sub = new StrSubstitutor(map, "<", ">", '!', "||");
- assertEquals("Hi < commons", sub.replace("Hi !< <name2||commons>"));
- }
-
- //-----------------------------------------------------------------------
- /**
- * Tests get set.
- */
- @Test
- public void testGetSetEscape() {
- final StrSubstitutor sub = new StrSubstitutor();
- assertEquals('$', sub.getEscapeChar());
- sub.setEscapeChar('<');
- assertEquals('<', sub.getEscapeChar());
- }
-
- /**
- * Tests get set.
- */
- @Test
- public void testGetSetPrefix() {
- final StrSubstitutor sub = new StrSubstitutor();
- assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher);
- sub.setVariablePrefix('<');
- assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.CharMatcher);
-
- sub.setVariablePrefix("<<");
- assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher);
- try {
- sub.setVariablePrefix((String) null);
- fail();
- } catch (final IllegalArgumentException ex) {
- // expected
- }
- assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher);
-
- final StrMatcher matcher = StrMatcher.commaMatcher();
- sub.setVariablePrefixMatcher(matcher);
- assertSame(matcher, sub.getVariablePrefixMatcher());
- try {
- sub.setVariablePrefixMatcher((StrMatcher) null);
- fail();
- } catch (final IllegalArgumentException ex) {
- // expected
- }
- assertSame(matcher, sub.getVariablePrefixMatcher());
- }
-
- /**
- * Tests get set.
- */
- @Test
- public void testGetSetSuffix() {
- final StrSubstitutor sub = new StrSubstitutor();
- assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher);
- sub.setVariableSuffix('<');
- assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.CharMatcher);
-
- sub.setVariableSuffix("<<");
- assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher);
- try {
- sub.setVariableSuffix((String) null);
- fail();
- } catch (final IllegalArgumentException ex) {
- // expected
- }
- assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher);
-
- final StrMatcher matcher = StrMatcher.commaMatcher();
- sub.setVariableSuffixMatcher(matcher);
- assertSame(matcher, sub.getVariableSuffixMatcher());
- try {
- sub.setVariableSuffixMatcher((StrMatcher) null);
- fail();
- } catch (final IllegalArgumentException ex) {
- // expected
- }
- assertSame(matcher, sub.getVariableSuffixMatcher());
- }
-
- /**
- * Tests get set.
- */
- @Test
- public void testGetSetValueDelimiter() {
- final StrSubstitutor sub = new StrSubstitutor();
- assertTrue(sub.getValueDelimiterMatcher() instanceof StrMatcher.StringMatcher);
- sub.setValueDelimiter(':');
- assertTrue(sub.getValueDelimiterMatcher() instanceof StrMatcher.CharMatcher);
-
- sub.setValueDelimiter("||");
- assertTrue(sub.getValueDelimiterMatcher() instanceof StrMatcher.StringMatcher);
- sub.setValueDelimiter((String) null);
- assertNull(sub.getValueDelimiterMatcher());
-
- final StrMatcher matcher = StrMatcher.commaMatcher();
- sub.setValueDelimiterMatcher(matcher);
- assertSame(matcher, sub.getValueDelimiterMatcher());
- sub.setValueDelimiterMatcher((StrMatcher) null);
- assertNull(sub.getValueDelimiterMatcher());
- }
-
- //-----------------------------------------------------------------------
- /**
- * Tests static.
- */
- @Test
- public void testStaticReplace() {
- final Map<String, String> map = new HashMap<>();
- map.put("name", "commons");
- assertEquals("Hi commons!", StrSubstitutor.replace("Hi ${name}!", map));
- }
-
- /**
- * Tests static.
- */
- @Test
- public void testStaticReplacePrefixSuffix() {
- final Map<String, String> map = new HashMap<>();
- map.put("name", "commons");
- assertEquals("Hi commons!", StrSubstitutor.replace("Hi <name>!", map, "<", ">"));
- }
-
- /**
- * Tests interpolation with system properties.
- */
- @Test
- public void testStaticReplaceSystemProperties() {
- final StrBuilder buf = new StrBuilder();
- buf.append("Hi ").append(System.getProperty("user.name"));
- buf.append(", you are working with ");
- buf.append(System.getProperty("os.name"));
- buf.append(", your home directory is ");
- buf.append(System.getProperty("user.home")).append('.');
- assertEquals(buf.toString(), StrSubstitutor.replaceSystemProperties("Hi ${user.name}, you are "
- + "working with ${os.name}, your home "
- + "directory is ${user.home}."));
- }
-
- /**
- * Test for LANG-1055: StrSubstitutor.replaceSystemProperties does not work consistently
- */
- @Test
- public void testLANG1055() {
- System.setProperty("test_key", "test_value");
-
- final String expected = StrSubstitutor.replace("test_key=${test_key}", System.getProperties());
- final String actual = StrSubstitutor.replaceSystemProperties("test_key=${test_key}");
- assertEquals(expected, actual);
- }
-
- /**
- * Test the replace of a properties object
- */
- @Test
- public void testSubstituteDefaultProperties() {
- final String org = "${doesnotwork}";
- System.setProperty("doesnotwork", "It works!");
-
- // create a new Properties object with the System.getProperties as default
- final Properties props = new Properties(System.getProperties());
-
- assertEquals("It works!", StrSubstitutor.replace(org, props));
- }
-
- @Test
- public void testSamePrefixAndSuffix() {
- final Map<String, String> map = new HashMap<>();
- map.put("greeting", "Hello");
- map.put(" there ", "XXX");
- map.put("name", "commons");
- assertEquals("Hi commons!", StrSubstitutor.replace("Hi @name@!", map, "@", "@"));
- assertEquals("Hello there commons!", StrSubstitutor.replace("@greeting@ there @name@!", map, "@", "@"));
- }
-
- @Test
- public void testSubstitutePreserveEscape() {
- final String org = "${not-escaped} $${escaped}";
- final Map<String, String> map = new HashMap<>();
- map.put("not-escaped", "value");
-
- final StrSubstitutor sub = new StrSubstitutor(map, "${", "}", '$');
- assertFalse(sub.isPreserveEscapes());
- assertEquals("value ${escaped}", sub.replace(org));
-
- sub.setPreserveEscapes(true);
- assertTrue(sub.isPreserveEscapes());
- assertEquals("value $${escaped}", sub.replace(org));
- }
-
- private void doTestReplace(final String expectedResult, final String replaceTemplate, final boolean substring) {
- final StrSubstitutor sub = new StrSubstitutor(values);
- doTestReplace(sub, expectedResult, replaceTemplate, substring);
- }
-
- //-----------------------------------------------------------------------
- private void doTestReplace(final StrSubstitutor sub, final String expectedResult, final String replaceTemplate,
- final boolean substring) {
- final String expectedShortResult = expectedResult.substring(1, expectedResult.length() - 1);
-
- // replace using String
- assertEquals(expectedResult, sub.replace(replaceTemplate));
- if (substring) {
- assertEquals(expectedShortResult, sub.replace(replaceTemplate, 1, replaceTemplate.length() - 2));
- }
-
- // replace using char[]
- final char[] chars = replaceTemplate.toCharArray();
- assertEquals(expectedResult, sub.replace(chars));
- if (substring) {
- assertEquals(expectedShortResult, sub.replace(chars, 1, chars.length - 2));
- }
-
- // replace using StringBuffer
- StringBuffer buf = new StringBuffer(replaceTemplate);
- assertEquals(expectedResult, sub.replace(buf));
- if (substring) {
- assertEquals(expectedShortResult, sub.replace(buf, 1, buf.length() - 2));
- }
-
- // replace using StringBuilder
- StringBuilder builder = new StringBuilder(replaceTemplate);
- assertEquals(expectedResult, sub.replace(builder));
- if (substring) {
- assertEquals(expectedShortResult, sub.replace(builder, 1, builder.length() - 2));
- }
-
- // replace using StrBuilder
- StrBuilder bld = new StrBuilder(replaceTemplate);
- assertEquals(expectedResult, sub.replace(bld));
- if (substring) {
- assertEquals(expectedShortResult, sub.replace(bld, 1, bld.length() - 2));
- }
-
- // replace using object
- final MutableObject<String> obj = new MutableObject<>(replaceTemplate); // toString returns template
- assertEquals(expectedResult, sub.replace(obj));
-
- // replace in StringBuffer
- buf = new StringBuffer(replaceTemplate);
- assertTrue(sub.replaceIn(buf));
- assertEquals(expectedResult, buf.toString());
- if (substring) {
- buf = new StringBuffer(replaceTemplate);
- assertTrue(sub.replaceIn(buf, 1, buf.length() - 2));
- assertEquals(expectedResult, buf.toString()); // expect full result as remainder is untouched
- }
-
- // replace in StringBuilder
- builder = new StringBuilder(replaceTemplate);
- assertTrue(sub.replaceIn(builder));
- assertEquals(expectedResult, builder.toString());
- if (substring) {
- builder = new StringBuilder(replaceTemplate);
- assertTrue(sub.replaceIn(builder, 1, builder.length() - 2));
- assertEquals(expectedResult, builder.toString()); // expect full result as remainder is untouched
- }
-
- // replace in StrBuilder
- bld = new StrBuilder(replaceTemplate);
- assertTrue(sub.replaceIn(bld));
- assertEquals(expectedResult, bld.toString());
- if (substring) {
- bld = new StrBuilder(replaceTemplate);
- assertTrue(sub.replaceIn(bld, 1, bld.length() - 2));
- assertEquals(expectedResult, bld.toString()); // expect full result as remainder is untouched
- }
- }
-
- private void doTestNoReplace(final String replaceTemplate) {
- final StrSubstitutor sub = new StrSubstitutor(values);
-
- if (replaceTemplate == null) {
- assertNull(sub.replace((String) null));
- assertNull(sub.replace((String) null, 0, 100));
- assertNull(sub.replace((char[]) null));
- assertNull(sub.replace((char[]) null, 0, 100));
- assertNull(sub.replace((StringBuffer) null));
- assertNull(sub.replace((StringBuffer) null, 0, 100));
- assertNull(sub.replace((StrBuilder) null));
- assertNull(sub.replace((StrBuilder) null, 0, 100));
- assertNull(sub.replace((Object) null));
- assertFalse(sub.replaceIn((StringBuffer) null));
- assertFalse(sub.replaceIn((StringBuffer) null, 0, 100));
- assertFalse(sub.replaceIn((StrBuilder) null));
- assertFalse(sub.replaceIn((StrBuilder) null, 0, 100));
- } else {
- assertEquals(replaceTemplate, sub.replace(replaceTemplate));
- final StrBuilder bld = new StrBuilder(replaceTemplate);
- assertFalse(sub.replaceIn(bld));
- assertEquals(replaceTemplate, bld.toString());
- }
- }
-
- @Test
- public void testReplaceInTakingTwoAndThreeIntsReturningFalse() {
- final Map<String, Object> hashMap = new HashMap<>();
- final StrLookup.MapStrLookup<Object> strLookupMapStrLookup = new StrLookup.MapStrLookup<>(hashMap);
- final StrMatcher strMatcher = StrMatcher.tabMatcher();
- final StrSubstitutor strSubstitutor =
- new StrSubstitutor(strLookupMapStrLookup, strMatcher, strMatcher, 'b', strMatcher);
-
- assertFalse(strSubstitutor.replaceIn((StringBuilder) null, 1315, (-1369)));
- assertEquals('b', strSubstitutor.getEscapeChar());
- assertFalse(strSubstitutor.isPreserveEscapes());
- }
-
- @Test
- public void testReplaceInTakingStringBuilderWithNonNull() {
- final StrLookup<String> strLookup = StrLookup.systemPropertiesLookup();
- final StrSubstitutor strSubstitutor = new StrSubstitutor(strLookup, "b<H", "b<H", '\'');
- final StringBuilder stringBuilder = new StringBuilder((CharSequence) "b<H");
-
- assertEquals('\'', strSubstitutor.getEscapeChar());
- assertFalse(strSubstitutor.replaceIn(stringBuilder));
- }
-
- @Test
- public void testReplaceInTakingStringBufferWithNonNull() {
- final StrSubstitutor strSubstitutor =
- new StrSubstitutor(new HashMap<String, String>(), "WV@i#y?N*[", "WV@i#y?N*[", '*');
-
- assertFalse(strSubstitutor.isPreserveEscapes());
- assertFalse(strSubstitutor.replaceIn(new StringBuffer("WV@i#y?N*[")));
- assertEquals('*', strSubstitutor.getEscapeChar());
- }
-
- @Test
- public void testCreatesStrSubstitutorTakingStrLookupAndCallsReplaceTakingTwoAndThreeInts() {
- final Map<String, CharacterPredicates> map = new HashMap<>();
- final StrLookup.MapStrLookup<CharacterPredicates> strLookupMapStrLookup = new StrLookup.MapStrLookup<>(map);
- final StrSubstitutor strSubstitutor = new StrSubstitutor(strLookupMapStrLookup);
-
- assertNull(strSubstitutor.replace((CharSequence) null, 0, 0));
- assertEquals('$', strSubstitutor.getEscapeChar());
- }
-
- @Test
- public void testReplaceTakingCharSequenceReturningNull() {
- final StrSubstitutor strSubstitutor = new StrSubstitutor((StrLookup<?>) null);
-
- assertNull(strSubstitutor.replace((CharSequence) null));
- assertFalse(strSubstitutor.isPreserveEscapes());
- assertEquals('$', strSubstitutor.getEscapeChar());
- }
-
- @Test(expected = NullPointerException.class)
- public void testReplaceTakingThreeArgumentsThrowsNullPointerException() {
- StrSubstitutor.replace(null, (Properties) null);
- }
-
- @Test
- public void testReplaceInTakingStringBuilderWithNull() {
- final Map<String, Object> map = new HashMap<>();
- final StrSubstitutor strSubstitutor = new StrSubstitutor(map, "", "", 'T', "K+<'f");
-
- assertFalse(strSubstitutor.replaceIn((StringBuilder) null));
- }
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.text;
+
+import static org.assertj.core.api.Assertions.assertThatNullPointerException;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import org.apache.commons.lang3.mutable.MutableObject;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Test class for {@link StrSubstitutor}.
+ *
+ * @deprecated This class will be removed in 2.0.
+ */
+@Deprecated
+public class StrSubstitutorTest {
+
+ private Map<String, String> values;
+
+ @BeforeEach
+ public void setUp() throws Exception {
+ values = new HashMap<>();
+ values.put("animal", "quick brown fox");
+ values.put("target", "lazy dog");
+ }
+
+ @AfterEach
+ public void tearDown() throws Exception {
+ values = null;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Tests simple key replace.
+ */
+ @Test
+ public void testReplaceSimple() {
+ doTestReplace("The quick brown fox jumps over the lazy dog.", "The ${animal} jumps over the ${target}.", true);
+ }
+
+ /**
+ * Tests simple key replace.
+ */
+ @Test
+ public void testReplaceSolo() {
+ doTestReplace("quick brown fox", "${animal}", false);
+ }
+
+ /**
+ * Tests replace with no variables.
+ */
+ @Test
+ public void testReplaceNoVariables() {
+ doTestNoReplace("The balloon arrived.");
+ }
+
+ /**
+ * Tests replace with null.
+ */
+ @Test
+ public void testReplaceNull() {
+ doTestNoReplace(null);
+ }
+
+ /**
+ * Tests replace with null.
+ */
+ @Test
+ public void testReplaceEmpty() {
+ doTestNoReplace("");
+ }
+
+ /**
+ * Tests key replace changing map after initialization (not recommended).
+ */
+ @Test
+ public void testReplaceChangedMap() {
+ final StrSubstitutor sub = new StrSubstitutor(values);
+ values.put("target", "moon");
+ assertEquals("The quick brown fox jumps over the moon.",
+ sub.replace("The ${animal} jumps over the ${target}."));
+ }
+
+ /**
+ * Tests unknown key replace.
+ */
+ @Test
+ public void testReplaceUnknownKey() {
+ doTestReplace("The ${person} jumps over the lazy dog.", "The ${person} jumps over the ${target}.", true);
+ doTestReplace("The ${person} jumps over the lazy dog. 1234567890.",
+ "The ${person} jumps over the ${target}. ${undefined.number:-1234567890}.", true);
+ }
+
+ /**
+ * Tests adjacent keys.
+ */
+ @Test
+ public void testReplaceAdjacentAtStart() {
+ values.put("code", "GBP");
+ values.put("amount", "12.50");
+ final StrSubstitutor sub = new StrSubstitutor(values);
+ assertEquals("GBP12.50 charged", sub.replace("${code}${amount} charged"));
+ }
+
+ /**
+ * Tests adjacent keys.
+ */
+ @Test
+ public void testReplaceAdjacentAtEnd() {
+ values.put("code", "GBP");
+ values.put("amount", "12.50");
+ final StrSubstitutor sub = new StrSubstitutor(values);
+ assertEquals("Amount is GBP12.50", sub.replace("Amount is ${code}${amount}"));
+ }
+
+ /**
+ * Tests simple recursive replace.
+ */
+ @Test
+ public void testReplaceRecursive() {
+ values.put("animal", "${critter}");
+ values.put("target", "${pet}");
+ values.put("pet", "${petCharacteristic} dog");
+ values.put("petCharacteristic", "lazy");
+ values.put("critter", "${critterSpeed} ${critterColor} ${critterType}");
+ values.put("critterSpeed", "quick");
+ values.put("critterColor", "brown");
+ values.put("critterType", "fox");
+ doTestReplace("The quick brown fox jumps over the lazy dog.", "The ${animal} jumps over the ${target}.", true);
+
+ values.put("pet", "${petCharacteristicUnknown:-lazy} dog");
+ doTestReplace("The quick brown fox jumps over the lazy dog.", "The ${animal} jumps over the ${target}.", true);
+ }
+
+ @Test
+ public void testDisableSubstitutionInValues() {
+ final StrSubstitutor sub = new StrSubstitutor(values);
+ sub.setDisableSubstitutionInValues(true);
+ values.put("animal", "${critter}");
+ values.put("target", "${pet}");
+ values.put("pet", "${petCharacteristic} dog");
+ values.put("petCharacteristic", "lazy");
+ values.put("critter", "${critterSpeed} ${critterColor} ${critterType}");
+ values.put("critterSpeed", "quick");
+ values.put("critterColor", "brown");
+ values.put("critterType", "fox");
+ doTestReplace(sub, "The ${critter} jumps over the ${pet}.", "The ${animal} jumps over the ${target}.", true);
+ }
+
+ /**
+ * Tests escaping.
+ */
+ @Test
+ public void testReplaceEscaping() {
+ doTestReplace("The ${animal} jumps over the lazy dog.", "The $${animal} jumps over the ${target}.", true);
+ }
+
+ /**
+ * Tests escaping.
+ */
+ @Test
+ public void testReplaceSoloEscaping() {
+ doTestReplace("${animal}", "$${animal}", false);
+ }
+
+ /**
+ * Tests complex escaping.
+ */
+ @Test
+ public void testReplaceComplexEscaping() {
+ doTestReplace("The ${quick brown fox} jumps over the lazy dog.",
+ "The $${${animal}} jumps over the ${target}.", true);
+ doTestReplace("The ${quick brown fox} jumps over the lazy dog. ${1234567890}.",
+ "The $${${animal}} jumps over the ${target}. $${${undefined.number:-1234567890}}.", true);
+ }
+
+ /**
+ * Tests when no prefix or suffix.
+ */
+ @Test
+ public void testReplaceNoPrefixNoSuffix() {
+ doTestReplace("The animal jumps over the lazy dog.", "The animal jumps over the ${target}.", true);
+ }
+
+ /**
+ * Tests when no incomplete prefix.
+ */
+ @Test
+ public void testReplaceIncompletePrefix() {
+ doTestReplace("The {animal} jumps over the lazy dog.", "The {animal} jumps over the ${target}.", true);
+ }
+
+ /**
+ * Tests when prefix but no suffix.
+ */
+ @Test
+ public void testReplacePrefixNoSuffix() {
+ doTestReplace("The ${animal jumps over the ${target} lazy dog.",
+ "The ${animal jumps over the ${target} ${target}.", true);
+ }
+
+ /**
+ * Tests when suffix but no prefix.
+ */
+ @Test
+ public void testReplaceNoPrefixSuffix() {
+ doTestReplace("The animal} jumps over the lazy dog.", "The animal} jumps over the ${target}.", true);
+ }
+
+ /**
+ * Tests when no variable name.
+ */
+ @Test
+ public void testReplaceEmptyKeys() {
+ doTestReplace("The ${} jumps over the lazy dog.", "The ${} jumps over the ${target}.", true);
+ doTestReplace("The animal jumps over the lazy dog.", "The ${:-animal} jumps over the ${target}.", true);
+ }
+
+ /**
+ * Tests replace creates output same as input.
+ */
+ @Test
+ public void testReplaceToIdentical() {
+ values.put("animal", "$${${thing}}");
+ values.put("thing", "animal");
+ doTestReplace("The ${animal} jumps.", "The ${animal} jumps.", true);
+ }
+
+ /**
+ * Tests a cyclic replace operation.
+ * The cycle should be detected and cause an exception to be thrown.
+ */
+ @Test
+ public void testCyclicReplacement() {
+ final Map<String, String> map = new HashMap<>();
+ map.put("animal", "${critter}");
+ map.put("target", "${pet}");
+ map.put("pet", "${petCharacteristic} dog");
+ map.put("petCharacteristic", "lazy");
+ map.put("critter", "${critterSpeed} ${critterColor} ${critterType}");
+ map.put("critterSpeed", "quick");
+ map.put("critterColor", "brown");
+ map.put("critterType", "${animal}");
+ StrSubstitutor sub = new StrSubstitutor(map);
+ try {
+ sub.replace("The ${animal} jumps over the ${target}.");
+ fail("Cyclic replacement was not detected!");
+ } catch (final IllegalStateException ex) {
+ // expected
+ }
+
+ // also check even when default value is set.
+ map.put("critterType", "${animal:-fox}");
+ sub = new StrSubstitutor(map);
+ try {
+ sub.replace("The ${animal} jumps over the ${target}.");
+ fail("Cyclic replacement was not detected!");
+ } catch (final IllegalStateException ex) {
+ // expected
+ }
+ }
+
+ /**
+ * Tests interpolation with weird boundary patterns.
+ */
+ @Test
+ public void testReplaceWeirdPattens() {
+ doTestNoReplace("");
+ doTestNoReplace("${}");
+ doTestNoReplace("${ }");
+ doTestNoReplace("${\t}");
+ doTestNoReplace("${\n}");
+ doTestNoReplace("${\b}");
+ doTestNoReplace("${");
+ doTestNoReplace("$}");
+ doTestNoReplace("}");
+ doTestNoReplace("${}$");
+ doTestNoReplace("${${");
+ doTestNoReplace("${${}}");
+ doTestNoReplace("${$${}}");
+ doTestNoReplace("${$$${}}");
+ doTestNoReplace("${$$${$}}");
+ doTestNoReplace("${${}}");
+ doTestNoReplace("${${ }}");
+ }
+
+ /**
+ * Tests simple key replace.
+ */
+ @Test
+ public void testReplacePartialString_noReplace() {
+ final StrSubstitutor sub = new StrSubstitutor();
+ assertEquals("${animal} jumps", sub.replace("The ${animal} jumps over the ${target}.", 4, 15));
+ }
+
+ /**
+ * Tests whether a variable can be replaced in a variable name.
+ */
+ @Test
+ public void testReplaceInVariable() {
+ values.put("animal.1", "fox");
+ values.put("animal.2", "mouse");
+ values.put("species", "2");
+ final StrSubstitutor sub = new StrSubstitutor(values);
+ sub.setEnableSubstitutionInVariables(true);
+ assertEquals(
+ "The mouse jumps over the lazy dog.",
+ sub.replace("The ${animal.${species}} jumps over the ${target}."));
+ values.put("species", "1");
+ assertEquals(
+ "The fox jumps over the lazy dog.",
+ sub.replace("The ${animal.${species}} jumps over the ${target}."));
+ assertEquals(
+ "The fox jumps over the lazy dog.",
+ sub.replace("The ${unknown.animal.${unknown.species:-1}:-fox} "
+ + "jumps over the ${unknow.target:-lazy dog}."));
+ }
+
+ /**
+ * Tests whether substitution in variable names is disabled per default.
+ */
+ @Test
+ public void testReplaceInVariableDisabled() {
+ values.put("animal.1", "fox");
+ values.put("animal.2", "mouse");
+ values.put("species", "2");
+ final StrSubstitutor sub = new StrSubstitutor(values);
+ assertEquals(
+ "The ${animal.${species}} jumps over the lazy dog.",
+ sub.replace("The ${animal.${species}} jumps over the ${target}."));
+ assertEquals(
+ "The ${animal.${species:-1}} jumps over the lazy dog.",
+ sub.replace("The ${animal.${species:-1}} jumps over the ${target}."));
+ }
+
+ /**
+ * Tests complex and recursive substitution in variable names.
+ */
+ @Test
+ public void testReplaceInVariableRecursive() {
+ values.put("animal.2", "brown fox");
+ values.put("animal.1", "white mouse");
+ values.put("color", "white");
+ values.put("species.white", "1");
+ values.put("species.brown", "2");
+ final StrSubstitutor sub = new StrSubstitutor(values);
+ sub.setEnableSubstitutionInVariables(true);
+ assertEquals(
+ "The white mouse jumps over the lazy dog.",
+ sub.replace("The ${animal.${species.${color}}} jumps over the ${target}."));
+ assertEquals(
+ "The brown fox jumps over the lazy dog.",
+ sub.replace("The ${animal.${species.${unknownColor:-brown}}} jumps over the ${target}."));
+ }
+
+ @Test
+ public void testDefaultValueDelimiters() {
+ final Map<String, String> map = new HashMap<>();
+ map.put("animal", "fox");
+ map.put("target", "dog");
+
+ StrSubstitutor sub = new StrSubstitutor(map, "${", "}", '$');
+ assertEquals("The fox jumps over the lazy dog. 1234567890.",
+ sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number:-1234567890}."));
+
+ sub = new StrSubstitutor(map, "${", "}", '$', "?:");
+ assertEquals("The fox jumps over the lazy dog. 1234567890.",
+ sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number?:1234567890}."));
+
+ sub = new StrSubstitutor(map, "${", "}", '$', "||");
+ assertEquals("The fox jumps over the lazy dog. 1234567890.",
+ sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number||1234567890}."));
+
+ sub = new StrSubstitutor(map, "${", "}", '$', "!");
+ assertEquals("The fox jumps over the lazy dog. 1234567890.",
+ sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number!1234567890}."));
+
+ sub = new StrSubstitutor(map, "${", "}", '$', "");
+ sub.setValueDelimiterMatcher(null);
+ assertEquals("The fox jumps over the lazy dog. ${undefined.number!1234567890}.",
+ sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number!1234567890}."));
+
+ sub = new StrSubstitutor(map, "${", "}", '$');
+ sub.setValueDelimiterMatcher(null);
+ assertEquals("The fox jumps over the lazy dog. ${undefined.number!1234567890}.",
+ sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number!1234567890}."));
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Tests protected.
+ */
+ @Test
+ public void testResolveVariable() {
+ final StrBuilder builder = new StrBuilder("Hi ${name}!");
+ final Map<String, String> map = new HashMap<>();
+ map.put("name", "commons");
+ final StrSubstitutor sub = new StrSubstitutor(map) {
+ @Override
+ protected String resolveVariable(final String variableName, final StrBuilder buf, final int startPos,
+ final int endPos) {
+ assertEquals("name", variableName);
+ assertSame(builder, buf);
+ assertEquals(3, startPos);
+ assertEquals(10, endPos);
+ return "jakarta";
+ }
+ };
+ sub.replaceIn(builder);
+ assertEquals("Hi jakarta!", builder.toString());
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Tests constructor.
+ */
+ @Test
+ public void testConstructorNoArgs() {
+ final StrSubstitutor sub = new StrSubstitutor();
+ assertEquals("Hi ${name}", sub.replace("Hi ${name}"));
+ }
+
+ /**
+ * Tests constructor.
+ */
+ @Test
+ public void testConstructorMapPrefixSuffix() {
+ final Map<String, String> map = new HashMap<>();
+ map.put("name", "commons");
+ final StrSubstitutor sub = new StrSubstitutor(map, "<", ">");
+ assertEquals("Hi < commons", sub.replace("Hi $< <name>"));
+ }
+
+ /**
+ * Tests constructor.
+ */
+ @Test
+ public void testConstructorMapFull() {
+ final Map<String, String> map = new HashMap<>();
+ map.put("name", "commons");
+ StrSubstitutor sub = new StrSubstitutor(map, "<", ">", '!');
+ assertEquals("Hi < commons", sub.replace("Hi !< <name>"));
+ sub = new StrSubstitutor(map, "<", ">", '!', "||");
+ assertEquals("Hi < commons", sub.replace("Hi !< <name2||commons>"));
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Tests get set.
+ */
+ @Test
+ public void testGetSetEscape() {
+ final StrSubstitutor sub = new StrSubstitutor();
+ assertEquals('$', sub.getEscapeChar());
+ sub.setEscapeChar('<');
+ assertEquals('<', sub.getEscapeChar());
+ }
+
+ /**
+ * Tests get set.
+ */
+ @Test
+ public void testGetSetPrefix() {
+ final StrSubstitutor sub = new StrSubstitutor();
+ assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher);
+ sub.setVariablePrefix('<');
+ assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.CharMatcher);
+
+ sub.setVariablePrefix("<<");
+ assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher);
+ try {
+ sub.setVariablePrefix((String) null);
+ fail("Exception expected!");
+ } catch (final IllegalArgumentException ex) {
+ // expected
+ }
+ assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher);
+
+ final StrMatcher matcher = StrMatcher.commaMatcher();
+ sub.setVariablePrefixMatcher(matcher);
+ assertSame(matcher, sub.getVariablePrefixMatcher());
+ try {
+ sub.setVariablePrefixMatcher((StrMatcher) null);
+ fail("Exception expected!");
+ } catch (final IllegalArgumentException ex) {
+ // expected
+ }
+ assertSame(matcher, sub.getVariablePrefixMatcher());
+ }
+
+ /**
+ * Tests get set.
+ */
+ @Test
+ public void testGetSetSuffix() {
+ final StrSubstitutor sub = new StrSubstitutor();
+ assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher);
+ sub.setVariableSuffix('<');
+ assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.CharMatcher);
+
+ sub.setVariableSuffix("<<");
+ assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher);
+ try {
+ sub.setVariableSuffix((String) null);
+ fail("Exception expected!");
+ } catch (final IllegalArgumentException ex) {
+ // expected
+ }
+ assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher);
+
+ final StrMatcher matcher = StrMatcher.commaMatcher();
+ sub.setVariableSuffixMatcher(matcher);
+ assertSame(matcher, sub.getVariableSuffixMatcher());
+ try {
+ sub.setVariableSuffixMatcher((StrMatcher) null);
+ fail("Exception expected!");
+ } catch (final IllegalArgumentException ex) {
+ // expected
+ }
+ assertSame(matcher, sub.getVariableSuffixMatcher());
+ }
+
+ /**
+ * Tests get set.
+ */
+ @Test
+ public void testGetSetValueDelimiter() {
+ final StrSubstitutor sub = new StrSubstitutor();
+ assertTrue(sub.getValueDelimiterMatcher() instanceof StrMatcher.StringMatcher);
+ sub.setValueDelimiter(':');
+ assertTrue(sub.getValueDelimiterMatcher() instanceof StrMatcher.CharMatcher);
+
+ sub.setValueDelimiter("||");
+ assertTrue(sub.getValueDelimiterMatcher() instanceof StrMatcher.StringMatcher);
+ sub.setValueDelimiter((String) null);
+ assertNull(sub.getValueDelimiterMatcher());
+
+ final StrMatcher matcher = StrMatcher.commaMatcher();
+ sub.setValueDelimiterMatcher(matcher);
+ assertSame(matcher, sub.getValueDelimiterMatcher());
+ sub.setValueDelimiterMatcher((StrMatcher) null);
+ assertNull(sub.getValueDelimiterMatcher());
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Tests static.
+ */
+ @Test
+ public void testStaticReplace() {
+ final Map<String, String> map = new HashMap<>();
+ map.put("name", "commons");
+ assertEquals("Hi commons!", StrSubstitutor.replace("Hi ${name}!", map));
+ }
+
+ /**
+ * Tests static.
+ */
+ @Test
+ public void testStaticReplacePrefixSuffix() {
+ final Map<String, String> map = new HashMap<>();
+ map.put("name", "commons");
+ assertEquals("Hi commons!", StrSubstitutor.replace("Hi <name>!", map, "<", ">"));
+ }
+
+ /**
+ * Tests interpolation with system properties.
+ */
+ @Test
+ public void testStaticReplaceSystemProperties() {
+ final StrBuilder buf = new StrBuilder();
+ buf.append("Hi ").append(System.getProperty("user.name"));
+ buf.append(", you are working with ");
+ buf.append(System.getProperty("os.name"));
+ buf.append(", your home directory is ");
+ buf.append(System.getProperty("user.home")).append('.');
+ assertEquals(buf.toString(), StrSubstitutor.replaceSystemProperties("Hi ${user.name}, you are "
+ + "working with ${os.name}, your home "
+ + "directory is ${user.home}."));
+ }
+
+ /**
+ * Test for LANG-1055: StrSubstitutor.replaceSystemProperties does not work consistently
+ */
+ @Test
+ public void testLANG1055() {
+ System.setProperty("test_key", "test_value");
+
+ final String expected = StrSubstitutor.replace("test_key=${test_key}", System.getProperties());
+ final String actual = StrSubstitutor.replaceSystemProperties("test_key=${test_key}");
+ assertEquals(expected, actual);
+ }
+
+ /**
+ * Test the replace of a properties object
+ */
+ @Test
+ public void testSubstituteDefaultProperties() {
+ final String org = "${doesnotwork}";
+ System.setProperty("doesnotwork", "It works!");
+
+ // create a new Properties object with the System.getProperties as default
+ final Properties props = new Properties(System.getProperties());
+
+ assertEquals("It works!", StrSubstitutor.replace(org, props));
+ }
+
+ @Test
+ public void testSamePrefixAndSuffix() {
+ final Map<String, String> map = new HashMap<>();
+ map.put("greeting", "Hello");
+ map.put(" there ", "XXX");
+ map.put("name", "commons");
+ assertEquals("Hi commons!", StrSubstitutor.replace("Hi @name@!", map, "@", "@"));
+ assertEquals("Hello there commons!", StrSubstitutor.replace("@greeting@ there @name@!", map, "@", "@"));
+ }
+
+ @Test
+ public void testSubstitutePreserveEscape() {
+ final String org = "${not-escaped} $${escaped}";
+ final Map<String, String> map = new HashMap<>();
+ map.put("not-escaped", "value");
+
+ final StrSubstitutor sub = new StrSubstitutor(map, "${", "}", '$');
+ assertFalse(sub.isPreserveEscapes());
+ assertEquals("value ${escaped}", sub.replace(org));
+
+ sub.setPreserveEscapes(true);
+ assertTrue(sub.isPreserveEscapes());
+ assertEquals("value $${escaped}", sub.replace(org));
+ }
+
+ private void doTestReplace(final String expectedResult, final String replaceTemplate, final boolean substring) {
+ final StrSubstitutor sub = new StrSubstitutor(values);
+ doTestReplace(sub, expectedResult, replaceTemplate, substring);
+ }
+
+ //-----------------------------------------------------------------------
+ private void doTestReplace(final StrSubstitutor sub, final String expectedResult, final String replaceTemplate,
+ final boolean substring) {
+ final String expectedShortResult = expectedResult.substring(1, expectedResult.length() - 1);
+
+ // replace using String
+ assertEquals(expectedResult, sub.replace(replaceTemplate));
+ if (substring) {
+ assertEquals(expectedShortResult, sub.replace(replaceTemplate, 1, replaceTemplate.length() - 2));
+ }
+
+ // replace using char[]
+ final char[] chars = replaceTemplate.toCharArray();
+ assertEquals(expectedResult, sub.replace(chars));
+ if (substring) {
+ assertEquals(expectedShortResult, sub.replace(chars, 1, chars.length - 2));
+ }
+
+ // replace using StringBuffer
+ StringBuffer buf = new StringBuffer(replaceTemplate);
+ assertEquals(expectedResult, sub.replace(buf));
+ if (substring) {
+ assertEquals(expectedShortResult, sub.replace(buf, 1, buf.length() - 2));
+ }
+
+ // replace using StringBuilder
+ StringBuilder builder = new StringBuilder(replaceTemplate);
+ assertEquals(expectedResult, sub.replace(builder));
+ if (substring) {
+ assertEquals(expectedShortResult, sub.replace(builder, 1, builder.length() - 2));
+ }
+
+ // replace using StrBuilder
+ StrBuilder bld = new StrBuilder(replaceTemplate);
+ assertEquals(expectedResult, sub.replace(bld));
+ if (substring) {
+ assertEquals(expectedShortResult, sub.replace(bld, 1, bld.length() - 2));
+ }
+
+ // replace using object
+ final MutableObject<String> obj = new MutableObject<>(replaceTemplate); // toString returns template
+ assertEquals(expectedResult, sub.replace(obj));
+
+ // replace in StringBuffer
+ buf = new StringBuffer(replaceTemplate);
+ assertTrue(sub.replaceIn(buf));
+ assertEquals(expectedResult, buf.toString());
+ if (substring) {
+ buf = new StringBuffer(replaceTemplate);
+ assertTrue(sub.replaceIn(buf, 1, buf.length() - 2));
+ assertEquals(expectedResult, buf.toString()); // expect full result as remainder is untouched
+ }
+
+ // replace in StringBuilder
+ builder = new StringBuilder(replaceTemplate);
+ assertTrue(sub.replaceIn(builder));
+ assertEquals(expectedResult, builder.toString());
+ if (substring) {
+ builder = new StringBuilder(replaceTemplate);
+ assertTrue(sub.replaceIn(builder, 1, builder.length() - 2));
+ assertEquals(expectedResult, builder.toString()); // expect full result as remainder is untouched
+ }
+
+ // replace in StrBuilder
+ bld = new StrBuilder(replaceTemplate);
+ assertTrue(sub.replaceIn(bld));
+ assertEquals(expectedResult, bld.toString());
+ if (substring) {
+ bld = new StrBuilder(replaceTemplate);
+ assertTrue(sub.replaceIn(bld, 1, bld.length() - 2));
+ assertEquals(expectedResult, bld.toString()); // expect full result as remainder is untouched
+ }
+ }
+
+ private void doTestNoReplace(final String replaceTemplate) {
+ final StrSubstitutor sub = new StrSubstitutor(values);
+
+ if (replaceTemplate == null) {
+ assertNull(sub.replace((String) null));
+ assertNull(sub.replace((String) null, 0, 100));
+ assertNull(sub.replace((char[]) null));
+ assertNull(sub.replace((char[]) null, 0, 100));
+ assertNull(sub.replace((StringBuffer) null));
+ assertNull(sub.replace((StringBuffer) null, 0, 100));
+ assertNull(sub.replace((StrBuilder) null));
+ assertNull(sub.replace((StrBuilder) null, 0, 100));
+ assertNull(sub.replace((Object) null));
+ assertFalse(sub.replaceIn((StringBuffer) null));
+ assertFalse(sub.replaceIn((StringBuffer) null, 0, 100));
+ assertFalse(sub.replaceIn((StrBuilder) null));
+ assertFalse(sub.replaceIn((StrBuilder) null, 0, 100));
+ } else {
+ assertEquals(replaceTemplate, sub.replace(replaceTemplate));
+ final StrBuilder bld = new StrBuilder(replaceTemplate);
+ assertFalse(sub.replaceIn(bld));
+ assertEquals(replaceTemplate, bld.toString());
+ }
+ }
+
+ @Test
+ public void testReplaceInTakingTwoAndThreeIntsReturningFalse() {
+ final Map<String, Object> hashMap = new HashMap<>();
+ final StrLookup.MapStrLookup<Object> strLookupMapStrLookup = new StrLookup.MapStrLookup<>(hashMap);
+ final StrMatcher strMatcher = StrMatcher.tabMatcher();
+ final StrSubstitutor strSubstitutor =
+ new StrSubstitutor(strLookupMapStrLookup, strMatcher, strMatcher, 'b', strMatcher);
+
+ assertFalse(strSubstitutor.replaceIn((StringBuilder) null, 1315, (-1369)));
+ assertEquals('b', strSubstitutor.getEscapeChar());
+ assertFalse(strSubstitutor.isPreserveEscapes());
+ }
+
+ @Test
+ public void testReplaceInTakingStringBuilderWithNonNull() {
+ final StrLookup<String> strLookup = StrLookup.systemPropertiesLookup();
+ final StrSubstitutor strSubstitutor = new StrSubstitutor(strLookup, "b<H", "b<H", '\'');
+ final StringBuilder stringBuilder = new StringBuilder((CharSequence) "b<H");
+
+ assertEquals('\'', strSubstitutor.getEscapeChar());
+ assertFalse(strSubstitutor.replaceIn(stringBuilder));
+ }
+
+ @Test
+ public void testReplaceInTakingStringBufferWithNonNull() {
+ final StrSubstitutor strSubstitutor =
+ new StrSubstitutor(new HashMap<String, String>(), "WV@i#y?N*[", "WV@i#y?N*[", '*');
+
+ assertFalse(strSubstitutor.isPreserveEscapes());
+ assertFalse(strSubstitutor.replaceIn(new StringBuffer("WV@i#y?N*[")));
+ assertEquals('*', strSubstitutor.getEscapeChar());
+ }
+
+ @Test
+ public void testCreatesStrSubstitutorTakingStrLookupAndCallsReplaceTakingTwoAndThreeInts() {
+ final Map<String, CharacterPredicates> map = new HashMap<>();
+ final StrLookup.MapStrLookup<CharacterPredicates> strLookupMapStrLookup = new StrLookup.MapStrLookup<>(map);
+ final StrSubstitutor strSubstitutor = new StrSubstitutor(strLookupMapStrLookup);
+
+ assertNull(strSubstitutor.replace((CharSequence) null, 0, 0));
+ assertEquals('$', strSubstitutor.getEscapeChar());
+ }
+
+ @Test
+ public void testReplaceTakingCharSequenceReturningNull() {
+ final StrSubstitutor strSubstitutor = new StrSubstitutor((StrLookup<?>) null);
+
+ assertNull(strSubstitutor.replace((CharSequence) null));
+ assertFalse(strSubstitutor.isPreserveEscapes());
+ assertEquals('$', strSubstitutor.getEscapeChar());
+ }
+
+ @Test
+ public void testReplaceTakingThreeArgumentsThrowsNullPointerException() {
+ assertThatNullPointerException().isThrownBy(() -> StrSubstitutor.replace(null, (Properties) null));
+ }
+
+ @Test
+ public void testReplaceInTakingStringBuilderWithNull() {
+ final Map<String, Object> map = new HashMap<>();
+ final StrSubstitutor strSubstitutor = new StrSubstitutor(map, "", "", 'T', "K+<'f");
+
+ assertFalse(strSubstitutor.replaceIn((StringBuilder) null));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/StrTokenizerTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/StrTokenizerTest.java b/src/test/java/org/apache/commons/text/StrTokenizerTest.java
index 35b9cd8..dc04b14 100644
--- a/src/test/java/org/apache/commons/text/StrTokenizerTest.java
+++ b/src/test/java/org/apache/commons/text/StrTokenizerTest.java
@@ -17,18 +17,18 @@
package org.apache.commons.text;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Unit test for {@link StrTokenizer}.
@@ -61,10 +61,10 @@ public class StrTokenizerTest {
final String[] expected = {"a", "b", "c", "d;\"e", "f", "", "", ""};
- assertEquals(Arrays.toString(tokens), expected.length, tokens.length);
+ assertEquals(expected.length, tokens.length, Arrays.toString(tokens));
for (int i = 0; i < expected.length; i++) {
- assertEquals("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
- expected[i], tokens[i]);
+ assertEquals(expected[i], tokens[i],
+ "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'");
}
}
@@ -82,10 +82,10 @@ public class StrTokenizerTest {
final String[] expected = {"a", "b", "c ", "d;\"e", "f", " ", " ", ""};
- assertEquals(Arrays.toString(tokens), expected.length, tokens.length);
+ assertEquals(expected.length, tokens.length, Arrays.toString(tokens));
for (int i = 0; i < expected.length; i++) {
- assertEquals("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
- expected[i], tokens[i]);
+ assertEquals(expected[i], tokens[i],
+ "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'");
}
}
@@ -103,10 +103,10 @@ public class StrTokenizerTest {
final String[] expected = {"a", "b", " c", "d;\"e", "f", " ", " ", ""};
- assertEquals(Arrays.toString(tokens), expected.length, tokens.length);
+ assertEquals(expected.length, tokens.length, Arrays.toString(tokens));
for (int i = 0; i < expected.length; i++) {
- assertEquals("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
- expected[i], tokens[i]);
+ assertEquals(expected[i], tokens[i],
+ "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'");
}
}
@@ -124,10 +124,10 @@ public class StrTokenizerTest {
final String[] expected = {"a", "b", "c", "d;\"e", "f"};
- assertEquals(Arrays.toString(tokens), expected.length, tokens.length);
+ assertEquals(expected.length, tokens.length, Arrays.toString(tokens));
for (int i = 0; i < expected.length; i++) {
- assertEquals("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
- expected[i], tokens[i]);
+ assertEquals(expected[i], tokens[i],
+ "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'");
}
}
@@ -146,10 +146,10 @@ public class StrTokenizerTest {
final String[] expected = {"a", "b", "c", "d;\"e", "f", null, null, null};
- assertEquals(Arrays.toString(tokens), expected.length, tokens.length);
+ assertEquals(expected.length, tokens.length, Arrays.toString(tokens));
for (int i = 0; i < expected.length; i++) {
- assertEquals("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
- expected[i], tokens[i]);
+ assertEquals(expected[i], tokens[i],
+ "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'");
}
}
@@ -180,14 +180,11 @@ public class StrTokenizerTest {
prevCount++;
}
- assertEquals(Arrays.toString(tokens), expected.length, tokens.length);
-
- assertTrue("could not cycle through entire token list" + " using the 'hasNext' and 'next' methods",
- nextCount == expected.length);
-
- assertTrue("could not cycle through entire token list" + " using the 'hasPrevious' and 'previous' methods",
- prevCount == expected.length);
-
+ assertEquals(expected.length, tokens.length, Arrays.toString(tokens));
+ assertTrue(nextCount == expected.length,
+ "could not cycle through entire token list using the 'hasNext' and 'next' methods");
+ assertTrue(prevCount == expected.length,
+ "could not cycle through entire token list using the 'hasPrevious' and 'previous' methods");
}
@Test
@@ -203,10 +200,10 @@ public class StrTokenizerTest {
final String[] expected = {"a", "", "", "b", "c", "d e", "f", ""};
- assertEquals(Arrays.toString(tokens), expected.length, tokens.length);
+ assertEquals(expected.length, tokens.length, Arrays.toString(tokens));
for (int i = 0; i < expected.length; i++) {
- assertEquals("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
- expected[i], tokens[i]);
+ assertEquals(expected[i], tokens[i],
+ "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'");
}
}
@@ -224,10 +221,10 @@ public class StrTokenizerTest {
final String[] expected = {"a", "b", "c", "d e", "f"};
- assertEquals(Arrays.toString(tokens), expected.length, tokens.length);
+ assertEquals(expected.length, tokens.length, Arrays.toString(tokens));
for (int i = 0; i < expected.length; i++) {
- assertEquals("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
- expected[i], tokens[i]);
+ assertEquals(expected[i], tokens[i],
+ "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'");
}
}
@@ -579,7 +576,7 @@ public class StrTokenizerTest {
assertEquals(0, tokenizer.size());
try {
tokenizer.next();
- fail();
+ fail("Exception expected!");
} catch (final NoSuchElementException ex) {
}
}
@@ -845,7 +842,7 @@ public class StrTokenizerTest {
assertFalse(tkn.hasPrevious());
try {
tkn.previous();
- fail();
+ fail("Exception expected!");
} catch (final NoSuchElementException ex) {
}
assertTrue(tkn.hasNext());
@@ -853,17 +850,17 @@ public class StrTokenizerTest {
assertEquals("a", tkn.next());
try {
tkn.remove();
- fail();
+ fail("Exception expected!");
} catch (final UnsupportedOperationException ex) {
}
try {
tkn.set("x");
- fail();
+ fail("Exception expected!");
} catch (final UnsupportedOperationException ex) {
}
try {
tkn.add("y");
- fail();
+ fail("Exception expected!");
} catch (final UnsupportedOperationException ex) {
}
assertTrue(tkn.hasPrevious());
@@ -879,7 +876,7 @@ public class StrTokenizerTest {
try {
tkn.next();
- fail();
+ fail("Exception expected!");
} catch (final NoSuchElementException ex) {
}
assertTrue(tkn.hasPrevious());
[4/4] [text] Update tests from JUnit 4 to 5. Closes #79.
Posted by gg...@apache.org.
Update tests from JUnit 4 to 5. Closes #79.
Project: http://git-wip-us.apache.org/repos/asf/commons-text/repo
Commit: http://git-wip-us.apache.org/repos/asf/commons-text/commit/49db4cb3
Tree: http://git-wip-us.apache.org/repos/asf/commons-text/tree/49db4cb3
Diff: http://git-wip-us.apache.org/repos/asf/commons-text/diff/49db4cb3
Branch: refs/heads/master
Commit: 49db4cb38baa24348023258924e63e9dac786f00
Parents: 6f06de9
Author: Pascal Schumacher <pa...@apache.org>
Authored: Sun Apr 8 09:42:14 2018 -0600
Committer: Gary Gregory <ga...@gmail.com>
Committed: Sun Apr 8 09:42:14 2018 -0600
----------------------------------------------------------------------
pom.xml | 32 +-
.../commons/text/AlphabetConverterTest.java | 87 +-
.../org/apache/commons/text/CaseUtilsTest.java | 2 +-
.../commons/text/CharacterPredicatesTest.java | 2 +-
.../commons/text/CompositeFormatTest.java | 8 +-
.../commons/text/ExtendedMessageFormatTest.java | 126 +-
.../commons/text/FormattableUtilsTest.java | 14 +-
.../commons/text/RandomStringGeneratorTest.java | 68 +-
.../text/StrBuilderAppendInsertTest.java | 2 +-
.../org/apache/commons/text/StrBuilderTest.java | 111 +-
.../org/apache/commons/text/StrLookupTest.java | 14 +-
.../org/apache/commons/text/StrMatcherTest.java | 2 +-
.../apache/commons/text/StrSubstitutorTest.java | 1664 +++++++++---------
.../apache/commons/text/StrTokenizerTest.java | 79 +-
.../commons/text/StringEscapeUtilsTest.java | 187 +-
.../commons/text/StringSubstitutorTest.java | 39 +-
...titutorWithInterpolatorStringLookupTest.java | 146 +-
.../commons/text/StringTokenizerTest.java | 79 +-
.../text/TextStringBuilderAppendInsertTest.java | 2 +-
.../commons/text/TextStringBuilderTest.java | 111 +-
.../org/apache/commons/text/WordUtilsTest.java | 15 +-
.../text/diff/ReplacementsFinderTest.java | 60 +-
.../text/diff/StringsComparatorTest.java | 10 +-
.../text/lookup/DateStringLookupTest.java | 100 +-
.../EnvironmentVariableStringLookupTest.java | 74 +-
.../lookup/InterpolatorStringLookupTest.java | 196 +--
.../lookup/JavaPlatformStringLookupTest.java | 63 +-
.../text/lookup/LocalHostStringLookupTest.java | 92 +-
.../text/lookup/MapStringLookupTest.java | 74 +-
.../text/lookup/NullStringLookupTest.java | 60 +-
.../lookup/ResourceBundleStringLookupTest.java | 70 +-
.../lookup/SystemPropertyStringLookupTest.java | 62 +-
.../commons/text/matcher/StringMatcherTest.java | 2 +-
.../matcher/StringSubstitutorGetSetTest.java | 18 +-
.../text/similarity/CosineDistanceTest.java | 6 +-
.../text/similarity/CosineSimilarityTest.java | 21 +-
.../commons/text/similarity/FuzzyScoreTest.java | 27 +-
.../text/similarity/HammingDistanceTest.java | 19 +-
.../text/similarity/JaccardDistanceTest.java | 56 +-
.../text/similarity/JaccardSimilarityTest.java | 56 +-
.../similarity/JaroWinklerDistanceTest.java | 29 +-
.../LevenshteinDetailedDistanceTest.java | 37 +-
.../similarity/LevenshteinDistanceTest.java | 27 +-
.../text/similarity/LevenshteinResultsTest.java | 2 +-
.../LongestCommonSubsequenceDistanceTest.java | 19 +-
.../LongestCommonSubsequenceTest.java | 49 +-
.../ParameterizedEditDistanceFromTest.java | 84 +-
.../ParameterizedLevenshteinDistanceTest.java | 121 +-
.../ParameterizedSimilarityScoreFromTest.java | 54 +-
.../similarity/SimilarityScoreFromTest.java | 7 +-
.../text/similarity/StringMetricFromTest.java | 18 +-
.../text/translate/AggregateTranslatorTest.java | 2 +-
.../text/translate/CodePointTranslatorTest.java | 2 +-
.../text/translate/CsvTranslatorsTest.java | 2 +-
.../text/translate/EntityArraysTest.java | 2 +-
.../text/translate/JavaUnicodeEscaperTest.java | 2 +-
.../text/translate/LookupTranslatorTest.java | 7 +-
.../translate/NumericEntityEscaperTest.java | 2 +-
.../translate/NumericEntityUnescaperTest.java | 2 +-
.../text/translate/OctalUnescaperTest.java | 2 +-
.../translate/SinglePassTranslatorTest.java | 15 +-
.../text/translate/UnicodeEscaperTest.java | 2 +-
.../text/translate/UnicodeUnescaperTest.java | 2 +-
.../UnicodeUnpairedSurrogateRemoverTest.java | 2 +-
64 files changed, 2185 insertions(+), 2162 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 8f872f9..241330e 100644
--- a/pom.xml
+++ b/pom.xml
@@ -48,6 +48,9 @@
<commons.distSvnStagingUrl>scm:svn:https://dist.apache.org/repos/dist/dev/commons/text/</commons.distSvnStagingUrl>
<commons.release.isDistModule>true</commons.release.isDistModule>
+ <junit.version>5.1.0</junit.version>
+ <junit.platform.version>1.1.0</junit.platform.version>
+
<checkstyle.plugin.version>3.0.0</checkstyle.plugin.version>
<checkstyle.version>8.9</checkstyle.version>
</properties>
@@ -60,15 +63,21 @@
</dependency>
<!-- testing -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <version>${junit.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-params</artifactId>
+ <version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.hamcrest</groupId>
- <artifactId>hamcrest-all</artifactId>
- <version>1.3</version>
+ <groupId>org.junit.platform</groupId>
+ <artifactId>junit-platform-launcher</artifactId>
+ <version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -99,6 +108,17 @@
</pluginManagement>
<plugins>
<plugin>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <version>2.19</version>
+ <dependencies>
+ <dependency>
+ <groupId>org.junit.platform</groupId>
+ <artifactId>junit-platform-surefire-provider</artifactId>
+ <version>${junit.platform.version}</version>
+ </dependency>
+ </dependencies>
+ </plugin>
+ <plugin>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${checkstyle.plugin.version}</version>
<configuration>
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/AlphabetConverterTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/AlphabetConverterTest.java b/src/test/java/org/apache/commons/text/AlphabetConverterTest.java
index 7eb8887..1ce32a7 100644
--- a/src/test/java/org/apache/commons/text/AlphabetConverterTest.java
+++ b/src/test/java/org/apache/commons/text/AlphabetConverterTest.java
@@ -22,11 +22,11 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Unit tests for {@link AlphabetConverter}.
@@ -55,14 +55,11 @@ public class AlphabetConverterTest {
108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122};
private static Integer[] doNotEncodeCodepoints = {32, 97, 98, 99}; // space, a, b, c
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
@Test
- public void encodeFailureTest() throws UnsupportedEncodingException {
- thrown.expect(UnsupportedEncodingException.class);
- thrown.expectMessage("Couldn't find encoding for '3'");
- test(binary, numbers, empty, "3");
+ public void encodeFailureTest() {
+ assertThatThrownBy(() -> {
+ test(binary, numbers, empty, "3");
+ }).isInstanceOf(UnsupportedEncodingException.class).hasMessage("Couldn't find encoding for '3' in 3");
}
@Test
@@ -117,23 +114,21 @@ public class AlphabetConverterTest {
@Test
public void unexpectedEndwhileDecodingTest() throws UnsupportedEncodingException {
final String toDecode = "00d01d0";
-
- thrown.expect(UnsupportedEncodingException.class);
- thrown.expectMessage("Unexpected end of string while decoding " + toDecode);
-
- final AlphabetConverter ac = createJavadocExample();
- ac.decode(toDecode);
+ assertThatThrownBy(() -> {
+ final AlphabetConverter ac = createJavadocExample();
+ ac.decode(toDecode);
+ }).isInstanceOf(UnsupportedEncodingException.class).hasMessage(
+ "Unexpected end of string while decoding " + toDecode);
}
@Test
public void unexpectedStringWhileDecodingTest() throws UnsupportedEncodingException {
final String toDecode = "00XX";
-
- thrown.expect(UnsupportedEncodingException.class);
- thrown.expectMessage("Unexpected string without decoding (XX) in " + toDecode);
-
- final AlphabetConverter ac = createJavadocExample();
- ac.decode(toDecode);
+ assertThatThrownBy(() -> {
+ final AlphabetConverter ac = createJavadocExample();
+ ac.decode(toDecode);
+ }).isInstanceOf(UnsupportedEncodingException.class).hasMessage(
+ "Unexpected string without decoding (XX) in " + toDecode);
}
/*
@@ -156,39 +151,37 @@ public class AlphabetConverterTest {
@Test
public void noEncodingLettersTest() {
- thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage(
+ assertThatThrownBy(() -> {
+ AlphabetConverter.createConverterFromChars(englishAndNumbers, numbers, numbers);
+ }).isInstanceOf(IllegalArgumentException.class).hasMessage(
"Must have at least two encoding characters (excluding those in the 'do not encode' list), but has 0");
-
- AlphabetConverter.createConverterFromChars(englishAndNumbers, numbers, numbers);
}
@Test
public void onlyOneEncodingLettersTest() {
- thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage(
- "Must have at least two encoding characters (excluding those in the 'do not encode' list), but has 1");
-
- final Character[] numbersPlusUnderscore = Arrays.copyOf(numbers, numbers.length + 1);
- numbersPlusUnderscore[numbersPlusUnderscore.length - 1] = '_';
+ assertThatThrownBy(() -> {
+ final Character[] numbersPlusUnderscore = Arrays.copyOf(numbers, numbers.length + 1);
+ numbersPlusUnderscore[numbersPlusUnderscore.length - 1] = '_';
- AlphabetConverter.createConverterFromChars(englishAndNumbers, numbersPlusUnderscore, numbers);
+ AlphabetConverter.createConverterFromChars(englishAndNumbers, numbersPlusUnderscore, numbers);
+ }).isInstanceOf(IllegalArgumentException.class).hasMessage(
+ "Must have at least two encoding characters (excluding those in the 'do not encode' list), but has 1");
}
@Test
public void missingDoNotEncodeLettersFromEncodingTest() {
- thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("Can not use 'do not encode' list because encoding alphabet does not contain");
-
- AlphabetConverter.createConverterFromChars(englishAndNumbers, lowerCaseEnglish, numbers);
+ assertThatThrownBy(() -> {
+ AlphabetConverter.createConverterFromChars(englishAndNumbers, lowerCaseEnglish, numbers);
+ }).isInstanceOf(IllegalArgumentException.class).hasMessage(
+ "Can not use 'do not encode' list because encoding alphabet does not contain '0'");
}
@Test
public void missingDoNotEncodeLettersFromOriginalTest() {
- thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("Can not use 'do not encode' list because original alphabet does not contain");
-
- AlphabetConverter.createConverterFromChars(lowerCaseEnglish, englishAndNumbers, numbers);
+ assertThatThrownBy(() -> {
+ AlphabetConverter.createConverterFromChars(lowerCaseEnglish, englishAndNumbers, numbers);
+ }).isInstanceOf(IllegalArgumentException.class).hasMessage(
+ "Can not use 'do not encode' list because original alphabet does not contain '0'");
}
private void test(final Character[] originalChars, final Character[] encodingChars,
@@ -229,13 +222,15 @@ public class AlphabetConverterTest {
}
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testCreateConverterFromCharsWithNullAndNull() {
- final Character[] characterArray = new Character[2];
- characterArray[0] = '$';
- characterArray[1] = characterArray[0];
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ final Character[] characterArray = new Character[2];
+ characterArray[0] = '$';
+ characterArray[1] = characterArray[0];
- AlphabetConverter.createConverterFromChars(characterArray, null, null);
+ AlphabetConverter.createConverterFromChars(characterArray, null, null);
+ });
}
@Test
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/CaseUtilsTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/CaseUtilsTest.java b/src/test/java/org/apache/commons/text/CaseUtilsTest.java
index 33ee577..c3f4353 100644
--- a/src/test/java/org/apache/commons/text/CaseUtilsTest.java
+++ b/src/test/java/org/apache/commons/text/CaseUtilsTest.java
@@ -16,7 +16,7 @@
*/
package org.apache.commons.text;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/CharacterPredicatesTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/CharacterPredicatesTest.java b/src/test/java/org/apache/commons/text/CharacterPredicatesTest.java
index e16ac13..53879e4 100644
--- a/src/test/java/org/apache/commons/text/CharacterPredicatesTest.java
+++ b/src/test/java/org/apache/commons/text/CharacterPredicatesTest.java
@@ -16,7 +16,7 @@
*/
package org.apache.commons.text;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/CompositeFormatTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/CompositeFormatTest.java b/src/test/java/org/apache/commons/text/CompositeFormatTest.java
index 0130f9b..24b3586 100644
--- a/src/test/java/org/apache/commons/text/CompositeFormatTest.java
+++ b/src/test/java/org/apache/commons/text/CompositeFormatTest.java
@@ -17,7 +17,7 @@
package org.apache.commons.text;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.text.FieldPosition;
import java.text.Format;
@@ -25,7 +25,7 @@ import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Locale;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link CompositeFormat}.
@@ -70,8 +70,8 @@ public class CompositeFormatTest {
composite.parseObject("", null);
composite.format(new Object(), new StringBuffer(), null);
- assertEquals("Parser get method incorrectly implemented", parser, composite.getParser());
- assertEquals("Formatter get method incorrectly implemented", formatter, composite.getFormatter());
+ assertEquals(parser, composite.getParser(), "Parser get method incorrectly implemented");
+ assertEquals(formatter, composite.getFormatter(), "Formatter get method incorrectly implemented");
}
@Test
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/ExtendedMessageFormatTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/ExtendedMessageFormatTest.java b/src/test/java/org/apache/commons/text/ExtendedMessageFormatTest.java
index 8770bc4..0563826 100644
--- a/src/test/java/org/apache/commons/text/ExtendedMessageFormatTest.java
+++ b/src/test/java/org/apache/commons/text/ExtendedMessageFormatTest.java
@@ -16,9 +16,11 @@
*/
package org.apache.commons.text;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.text.DateFormat;
import java.text.FieldPosition;
@@ -34,8 +36,8 @@ import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* Test case for {@link ExtendedMessageFormat}.
@@ -44,7 +46,7 @@ public class ExtendedMessageFormatTest {
private final Map<String, FormatFactory> registry = new HashMap<>();
- @Before
+ @BeforeEach
public void setUp() {
registry.put("lower", new LowerCaseFormatFactory());
registry.put("upper", new UpperCaseFormatFactory());
@@ -57,7 +59,7 @@ public class ExtendedMessageFormatTest {
public void testExtendedFormats() {
final String pattern = "Lower: {0,lower} Upper: {1,upper}";
final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
- assertEquals("TOPATTERN", pattern, emf.toPattern());
+ assertEquals(pattern, emf.toPattern(), "TOPATTERN");
assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"foo", "bar"}));
assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"Foo", "Bar"}));
assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"FOO", "BAR"}));
@@ -152,8 +154,8 @@ public class ExtendedMessageFormatTest {
expected.append(df.format(args[1]));
expected.append(" Salary: ");
expected.append(nf.format(args[2]));
- assertEquals("pattern comparison for locale " + locale, expectedPattern, emf.toPattern());
- assertEquals(String.valueOf(locale), expected.toString(), emf.format(args));
+ assertEquals(expectedPattern, emf.toPattern(), "pattern comparison for locale " + locale);
+ assertEquals(expected.toString(), emf.format(args), String.valueOf(locale));
}
}
@@ -278,8 +280,8 @@ public class ExtendedMessageFormatTest {
final MessageFormat dateDefault = createMessageFormat("{0,date}", locale);
final String pattern = "{0,date,short}";
final ExtendedMessageFormat dateShort = new ExtendedMessageFormat(pattern, locale, dateRegistry);
- assertEquals("overridden date,short format", dateDefault.format(args), dateShort.format(args));
- assertEquals("overridden date,short pattern", pattern, dateShort.toPattern());
+ assertEquals(dateDefault.format(args), dateShort.format(args), "overridden date,short format");
+ assertEquals(pattern, dateShort.toPattern(), "overridden date,short pattern");
}
}
@@ -290,11 +292,11 @@ public class ExtendedMessageFormatTest {
public void testBuiltInNumberFormat() {
final Object[] args = new Object[] {Double.valueOf("6543.21")};
final Locale[] availableLocales = NumberFormat.getAvailableLocales();
- checkBuiltInFormat("1: {0,number}", args, availableLocales);
- checkBuiltInFormat("2: {0,number,integer}", args, availableLocales);
- checkBuiltInFormat("3: {0,number,currency}", args, availableLocales);
- checkBuiltInFormat("4: {0,number,percent}", args, availableLocales);
- checkBuiltInFormat("5: {0,number,00000.000}", args, availableLocales);
+ checkBuiltInFormat("1: {0,number}", args, availableLocales);
+ checkBuiltInFormat("2: {0,number,integer}", args, availableLocales);
+ checkBuiltInFormat("3: {0,number,currency}", args, availableLocales);
+ checkBuiltInFormat("4: {0,number,percent}", args, availableLocales);
+ checkBuiltInFormat("5: {0,number,00000.000}", args, availableLocales);
}
/**
@@ -313,35 +315,35 @@ public class ExtendedMessageFormatTest {
ExtendedMessageFormat other = null;
// Same object
- assertTrue("same, equals()", emf.equals(emf));
- assertTrue("same, hashcode()", emf.hashCode() == emf.hashCode());
+ assertTrue(emf.equals(emf), "same, equals()");
+ assertEquals(emf.hashCode(), emf.hashCode(), "same, hashcode()");
- assertFalse("null, equals", emf.equals(null));
+ assertFalse(emf.equals(null), "null, equals");
// Equal Object
other = new ExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
- assertTrue("equal, equals()", emf.equals(other));
- assertTrue("equal, hashcode()", emf.hashCode() == other.hashCode());
+ assertTrue(emf.equals(other), "equal, equals()");
+ assertTrue(emf.hashCode() == other.hashCode(), "equal, hashcode()");
// Different Class
other = new OtherExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
- assertFalse("class, equals()", emf.equals(other));
- assertTrue("class, hashcode()", emf.hashCode() == other.hashCode()); // same hashcode
+ assertFalse(emf.equals(other), "class, equals()");
+ assertTrue(emf.hashCode() == other.hashCode(), "class, hashcode()"); // same hashcode
// Different pattern
other = new ExtendedMessageFormat("X" + pattern, Locale.US, fmtRegistry);
- assertFalse("pattern, equals()", emf.equals(other));
- assertFalse("pattern, hashcode()", emf.hashCode() == other.hashCode());
+ assertFalse(emf.equals(other), "pattern, equals()");
+ assertFalse(emf.hashCode() == other.hashCode(), "pattern, hashcode()");
// Different registry
other = new ExtendedMessageFormat(pattern, Locale.US, otherRegitry);
- assertFalse("registry, equals()", emf.equals(other));
- assertFalse("registry, hashcode()", emf.hashCode() == other.hashCode());
+ assertFalse(emf.equals(other), "registry, equals()");
+ assertFalse(emf.hashCode() == other.hashCode(), "registry, hashcode()");
// Different Locale
other = new ExtendedMessageFormat(pattern, Locale.FRANCE, fmtRegistry);
- assertFalse("locale, equals()", emf.equals(other));
- assertTrue("locale, hashcode()", emf.hashCode() == other.hashCode()); // same hashcode
+ assertFalse(emf.equals(other), "locale, equals()");
+ assertTrue(emf.hashCode() == other.hashCode(), "locale, hashcode()"); // same hashcode
}
/**
@@ -393,8 +395,8 @@ public class ExtendedMessageFormatTest {
} else {
emf = new ExtendedMessageFormat(pattern, locale);
}
- assertEquals("format " + buffer.toString(), mf.format(args), emf.format(args));
- assertEquals("toPattern " + buffer.toString(), mf.toPattern(), emf.toPattern());
+ assertEquals(mf.format(args), emf.format(args), "format " + buffer.toString());
+ assertEquals(mf.toPattern(), emf.toPattern(), "toPattern " + buffer.toString());
}
/**
@@ -412,53 +414,71 @@ public class ExtendedMessageFormatTest {
return result;
}
- @Test(expected = UnsupportedOperationException.class)
+ @Test
public void testSetFormatIsUnsupported() {
- final ExtendedMessageFormat emf = new ExtendedMessageFormat("");
- emf.setFormat(0, new LowerCaseFormat());
+ assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> {
+ final ExtendedMessageFormat emf = new ExtendedMessageFormat("");
+ emf.setFormat(0, new LowerCaseFormat());
+ });
}
- @Test(expected = UnsupportedOperationException.class)
+ @Test
public void testSetFormatByArgumentIndexIsUnsupported() {
- final ExtendedMessageFormat emf = new ExtendedMessageFormat("");
- emf.setFormatByArgumentIndex(0, new LowerCaseFormat());
+ assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> {
+ final ExtendedMessageFormat emf = new ExtendedMessageFormat("");
+ emf.setFormatByArgumentIndex(0, new LowerCaseFormat());
+ });
}
- @Test(expected = UnsupportedOperationException.class)
+ @Test
public void testSetFormatsIsUnsupported() {
- final ExtendedMessageFormat emf = new ExtendedMessageFormat("");
- emf.setFormats(new Format[]{new LowerCaseFormat(), new UpperCaseFormat()});
+ assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> {
+ final ExtendedMessageFormat emf = new ExtendedMessageFormat("");
+ emf.setFormats(new Format[] {new LowerCaseFormat(), new UpperCaseFormat()});
+ });
}
- @Test(expected = UnsupportedOperationException.class)
+ @Test
public void testSetFormatsByArgumentIndex() {
- final ExtendedMessageFormat emf = new ExtendedMessageFormat("");
- emf.setFormatsByArgumentIndex(new Format[]{new LowerCaseFormat(), new UpperCaseFormat()});
+ assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> {
+ final ExtendedMessageFormat emf = new ExtendedMessageFormat("");
+ emf.setFormatsByArgumentIndex(new Format[] {new LowerCaseFormat(), new UpperCaseFormat()});
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testFailsToCreateExtendedMessageFormatTakingTwoArgumentsThrowsIllegalArgumentExceptionOne() {
- new ExtendedMessageFormat("agdXdkR;T1{9 ^,LzXf?", new HashMap<String, FormatFactory>());
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ new ExtendedMessageFormat("agdXdkR;T1{9 ^,LzXf?", new HashMap<String, FormatFactory>());
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testFailsToCreateExtendedMessageFormatTakingTwoArgumentsThrowsIllegalArgumentExceptionTwo() {
- new ExtendedMessageFormat("a5XdkR;T1{9 ,LzXf?", new HashMap<String, FormatFactory>());
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ new ExtendedMessageFormat("a5XdkR;T1{9 ,LzXf?", new HashMap<String, FormatFactory>());
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testFailsToCreateExtendedMessageFormatTakingTwoArgumentsThrowsIllegalArgumentExceptionThree() {
- new ExtendedMessageFormat("9jLh_D9{ ", new HashMap<String, FormatFactory>());
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ new ExtendedMessageFormat("9jLh_D9{ ", new HashMap<String, FormatFactory>());
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testFailsToCreateExtendedMessageFormatTakingTwoArgumentsThrowsIllegalArgumentExceptionFour() {
- new ExtendedMessageFormat("RD,nXhM{}{", new HashMap<String, FormatFactory>());
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ new ExtendedMessageFormat("RD,nXhM{}{", new HashMap<String, FormatFactory>());
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testFailsToCreateExtendedMessageFormatTakingTwoArgumentsThrowsIllegalArgumentExceptionFive() {
- new ExtendedMessageFormat("j/[_D9{0,\"&'+0o", new HashMap<String, FormatFactory>());
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ new ExtendedMessageFormat("j/[_D9{0,\"&'+0o", new HashMap<String, FormatFactory>());
+ });
}
@Test
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/FormattableUtilsTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/FormattableUtilsTest.java b/src/test/java/org/apache/commons/text/FormattableUtilsTest.java
index 7741523..273cea1 100644
--- a/src/test/java/org/apache/commons/text/FormattableUtilsTest.java
+++ b/src/test/java/org/apache/commons/text/FormattableUtilsTest.java
@@ -18,11 +18,13 @@ package org.apache.commons.text;
import static java.util.FormattableFlags.LEFT_JUSTIFY;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+import static org.assertj.core.api.Assertions.assertThatNullPointerException;
import java.util.Formattable;
import java.util.Formatter;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Unit tests {@link FormattableUtils}.
@@ -107,9 +109,11 @@ public class FormattableUtilsTest {
.isEqualTo("+* ");
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testIllegalEllipsis() {
- FormattableUtils.append("foo", new Formatter(), 0, -1, 1, "xx");
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ FormattableUtils.append("foo", new Formatter(), 0, -1, 1, "xx");
+ });
}
@Test
@@ -146,9 +150,9 @@ public class FormattableUtilsTest {
.isEqualTo("+*___");
}
- @Test(expected = NullPointerException.class)
+ @Test
public void testAppendWithNullFormatterAndIntsThrowsNullPointerException() {
- FormattableUtils.append("", null, 0, 0, 0, '}');
+ assertThatNullPointerException().isThrownBy(() -> FormattableUtils.append("", null, 0, 0, 0, '}'));
}
static class SimplestFormattable implements Formattable {
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/RandomStringGeneratorTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/RandomStringGeneratorTest.java b/src/test/java/org/apache/commons/text/RandomStringGeneratorTest.java
index f6c40b1..7805b89 100644
--- a/src/test/java/org/apache/commons/text/RandomStringGeneratorTest.java
+++ b/src/test/java/org/apache/commons/text/RandomStringGeneratorTest.java
@@ -16,14 +16,12 @@
*/
package org.apache.commons.text;
-import static org.hamcrest.Matchers.allOf;
-import static org.hamcrest.Matchers.greaterThanOrEqualTo;
-import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
+import static org.assertj.core.api.Assertions.assertThatNullPointerException;
import static org.assertj.core.api.Assertions.fail;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests for {@link RandomStringGenerator}
@@ -44,22 +42,28 @@ public class RandomStringGeneratorTest {
}
};
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testInvalidLength() {
- final RandomStringGenerator generator = new RandomStringGenerator.Builder().build();
- generator.generate(-1);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ final RandomStringGenerator generator = new RandomStringGenerator.Builder().build();
+ generator.generate(-1);
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGenerateMinMaxLengthInvalidLength() {
- final RandomStringGenerator generator = new RandomStringGenerator.Builder().build();
- generator.generate(-1, 0);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ final RandomStringGenerator generator = new RandomStringGenerator.Builder().build();
+ generator.generate(-1, 0);
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testGenerateMinMaxLengthMinGreaterThanMax() {
- final RandomStringGenerator generator = new RandomStringGenerator.Builder().build();
- generator.generate(1, 0);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ final RandomStringGenerator generator = new RandomStringGenerator.Builder().build();
+ generator.generate(1, 0);
+ });
}
private static int codePointLength(final String s) {
@@ -80,17 +84,21 @@ public class RandomStringGeneratorTest {
final int maxLength = 3;
final RandomStringGenerator generator = new RandomStringGenerator.Builder().build();
final String str = generator.generate(minLength, maxLength);
- assertThat(codePointLength(str), allOf(greaterThanOrEqualTo(0), lessThanOrEqualTo(3)));
+ assertThat(codePointLength(str)).isBetween(0, 3);
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testBadMinimumCodePoint() {
- new RandomStringGenerator.Builder().withinRange(-1, 1);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ new RandomStringGenerator.Builder().withinRange(-1, 1);
+ });
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testBadMaximumCodePoint() {
- new RandomStringGenerator.Builder().withinRange(0, Character.MAX_CODE_POINT + 1);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ new RandomStringGenerator.Builder().withinRange(0, Character.MAX_CODE_POINT + 1);
+ });
}
@Test
@@ -216,9 +224,11 @@ public class RandomStringGeneratorTest {
} while (i < str.length());
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testBadMinAndMax() {
- new RandomStringGenerator.Builder().withinRange(2, 1);
+ assertThatIllegalArgumentException().isThrownBy(() -> {
+ new RandomStringGenerator.Builder().withinRange(2, 1);
+ });
}
@Test
@@ -279,13 +289,15 @@ public class RandomStringGeneratorTest {
}
}
- @Test(expected = NullPointerException.class)
+ @Test
public void testGenerateTakingIntThrowsNullPointerException() {
- final RandomStringGenerator.Builder randomStringGeneratorBuilder = new RandomStringGenerator.Builder();
- final CharacterPredicate[] characterPredicateArray = new CharacterPredicate[2];
- randomStringGeneratorBuilder.filteredBy(characterPredicateArray);
- final RandomStringGenerator randomStringGenerator = randomStringGeneratorBuilder.build();
-
- randomStringGenerator.generate(18);
+ assertThatNullPointerException().isThrownBy(() -> {
+ final RandomStringGenerator.Builder randomStringGeneratorBuilder = new RandomStringGenerator.Builder();
+ final CharacterPredicate[] characterPredicateArray = new CharacterPredicate[2];
+ randomStringGeneratorBuilder.filteredBy(characterPredicateArray);
+ final RandomStringGenerator randomStringGenerator = randomStringGeneratorBuilder.build();
+
+ randomStringGenerator.generate(18);
+ });
}
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/StrBuilderAppendInsertTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/StrBuilderAppendInsertTest.java b/src/test/java/org/apache/commons/text/StrBuilderAppendInsertTest.java
index e1cfad4..416e0ed 100644
--- a/src/test/java/org/apache/commons/text/StrBuilderAppendInsertTest.java
+++ b/src/test/java/org/apache/commons/text/StrBuilderAppendInsertTest.java
@@ -26,7 +26,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link StrBuilder}.
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/StrBuilderTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/StrBuilderTest.java b/src/test/java/org/apache/commons/text/StrBuilderTest.java
index 528588a..a7fafe2 100644
--- a/src/test/java/org/apache/commons/text/StrBuilderTest.java
+++ b/src/test/java/org/apache/commons/text/StrBuilderTest.java
@@ -17,14 +17,15 @@
package org.apache.commons.text;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.io.Reader;
@@ -36,7 +37,7 @@ import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link StrBuilder}.
@@ -482,13 +483,13 @@ public class StrBuilderTest {
assertEquals(0, sb.toCharArray().length);
char[] a = sb.toCharArray();
- assertNotNull("toCharArray() result is null", a);
- assertEquals("toCharArray() result is too large", 0, a.length);
+ assertNotNull(a, "toCharArray() result is null");
+ assertEquals(0, a.length, "toCharArray() result is too large");
sb.append("junit");
a = sb.toCharArray();
- assertEquals("toCharArray() result incorrect length", 5, a.length);
- assertTrue("toCharArray() result does not match", Arrays.equals("junit".toCharArray(), a));
+ assertEquals(5, a.length, "toCharArray() result incorrect length");
+ assertTrue(Arrays.equals("junit".toCharArray(), a), "toCharArray() result does not match");
}
@Test
@@ -498,19 +499,19 @@ public class StrBuilderTest {
sb.append("junit");
char[] a = sb.toCharArray(0, 20); // too large test
- assertEquals("toCharArray(int,int) result incorrect length", 5, a.length);
- assertTrue("toCharArray(int,int) result does not match", Arrays.equals("junit".toCharArray(), a));
+ assertEquals(5, a.length, "toCharArray(int,int) result incorrect length");
+ assertTrue(Arrays.equals("junit".toCharArray(), a), "toCharArray(int,int) result does not match");
a = sb.toCharArray(0, 4);
- assertEquals("toCharArray(int,int) result incorrect length", 4, a.length);
- assertTrue("toCharArray(int,int) result does not match", Arrays.equals("juni".toCharArray(), a));
+ assertEquals(4, a.length, "toCharArray(int,int) result incorrect length");
+ assertTrue(Arrays.equals("juni".toCharArray(), a), "toCharArray(int,int) result does not match");
a = sb.toCharArray(0, 4);
- assertEquals("toCharArray(int,int) result incorrect length", 4, a.length);
- assertTrue("toCharArray(int,int) result does not match", Arrays.equals("juni".toCharArray(), a));
+ assertEquals(4, a.length, "toCharArray(int,int) result incorrect length");
+ assertTrue(Arrays.equals("juni".toCharArray(), a), "toCharArray(int,int) result does not match");
a = sb.toCharArray(0, 1);
- assertNotNull("toCharArray(int,int) result is null", a);
+ assertNotNull(a, "toCharArray(int,int) result is null");
try {
sb.toCharArray(-1, 5);
@@ -1045,7 +1046,7 @@ public class StrBuilderTest {
sb = new StrBuilder("aaxaaaayaa");
try {
sb.replace(StrMatcher.stringMatcher("aa"), "-", 11, sb.length(), -1);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException ex) {
}
assertEquals("aaxaaaayaa", sb.toString());
@@ -1053,7 +1054,7 @@ public class StrBuilderTest {
sb = new StrBuilder("aaxaaaayaa");
try {
sb.replace(StrMatcher.stringMatcher("aa"), "-", -1, sb.length(), -1);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException ex) {
}
assertEquals("aaxaaaayaa", sb.toString());
@@ -1108,7 +1109,7 @@ public class StrBuilderTest {
sb = new StrBuilder("aaxaaaayaa");
try {
sb.replace(StrMatcher.stringMatcher("aa"), "-", 2, 1, -1);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException ex) {
}
assertEquals("aaxaaaayaa", sb.toString());
@@ -1216,28 +1217,28 @@ public class StrBuilderTest {
// Start index is negative
try {
sb.subSequence(-1, 5);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException e) {
}
// End index is negative
try {
sb.subSequence(2, -1);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException e) {
}
// End index greater than length()
try {
sb.subSequence(2, sb.length() + 1);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException e) {
}
// Start index greater then end index
try {
sb.subSequence(3, 2);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException e) {
}
@@ -1257,13 +1258,13 @@ public class StrBuilderTest {
assertEquals("hello goodbye".substring(0), sb.substring(0));
try {
sb.substring(-1);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException e) {
}
try {
sb.substring(15);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException e) {
}
@@ -1282,13 +1283,13 @@ public class StrBuilderTest {
try {
sb.substring(-1, 5);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException e) {
}
try {
sb.substring(15, 20);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException e) {
}
}
@@ -1765,27 +1766,27 @@ public class StrBuilderTest {
array = new char[3];
try {
reader.read(array, -1, 0);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException ex) {
}
try {
reader.read(array, 0, -1);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException ex) {
}
try {
reader.read(array, 100, 1);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException ex) {
}
try {
reader.read(array, 0, 100);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException ex) {
}
try {
reader.read(array, Integer.MAX_VALUE, Integer.MAX_VALUE);
- fail();
+ fail("Exception expected!");
} catch (final IndexOutOfBoundsException ex) {
}
@@ -1957,8 +1958,8 @@ public class StrBuilderTest {
public void testLang295() {
final StrBuilder sb = new StrBuilder("onetwothree");
sb.deleteFirst("three");
- assertFalse("The contains(char) method is looking beyond the end of the string", sb.contains('h'));
- assertEquals("The indexOf(char) method is looking beyond the end of the string", -1, sb.indexOf('h'));
+ assertFalse(sb.contains('h'), "The contains(char) method is looking beyond the end of the string");
+ assertEquals(-1, sb.indexOf('h'), "The indexOf(char) method is looking beyond the end of the string");
}
// -----------------------------------------------------------------------
@@ -1966,14 +1967,14 @@ public class StrBuilderTest {
public void testLang412Right() {
final StrBuilder sb = new StrBuilder();
sb.appendFixedWidthPadRight(null, 10, '*');
- assertEquals("Failed to invoke appendFixedWidthPadRight correctly", "**********", sb.toString());
+ assertEquals("**********", sb.toString(), "Failed to invoke appendFixedWidthPadRight correctly");
}
@Test
public void testLang412Left() {
final StrBuilder sb = new StrBuilder();
sb.appendFixedWidthPadLeft(null, 10, '*');
- assertEquals("Failed to invoke appendFixedWidthPadLeft correctly", "**********", sb.toString());
+ assertEquals("**********", sb.toString(), "Failed to invoke appendFixedWidthPadLeft correctly");
}
@Test
@@ -2122,27 +2123,33 @@ public class StrBuilderTest {
assertEquals("c" + System.lineSeparator(), sb1.appendln(ch).toString());
}
- @Test(expected = StringIndexOutOfBoundsException.class)
+ @Test
public void testAppendTakingTwoIntsWithZeroThrowsStringIndexOutOfBoundsException() {
- final Charset charset = Charset.defaultCharset();
- final ByteBuffer byteBuffer = charset.encode("end < start");
- final CharBuffer charBuffer = charset.decode(byteBuffer);
+ assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(() -> {
+ final Charset charset = Charset.defaultCharset();
+ final ByteBuffer byteBuffer = charset.encode("end < start");
+ final CharBuffer charBuffer = charset.decode(byteBuffer);
- new StrBuilder(630).append(charBuffer, 0, 630);
+ new StrBuilder(630).append(charBuffer, 0, 630);
+ });
}
- @Test(expected = StringIndexOutOfBoundsException.class)
+ @Test
public void testAppendTakingTwoIntsWithIndexOutOfBoundsThrowsStringIndexOutOfBoundsExceptionTwo() {
- final Charset charset = Charset.defaultCharset();
- final ByteBuffer byteBuffer = charset.encode("asdf");
- final CharBuffer charBuffer = charset.decode(byteBuffer);
+ assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(() -> {
+ final Charset charset = Charset.defaultCharset();
+ final ByteBuffer byteBuffer = charset.encode("asdf");
+ final CharBuffer charBuffer = charset.decode(byteBuffer);
- new StrBuilder().append(charBuffer, 933, 654);
+ new StrBuilder().append(charBuffer, 933, 654);
+ });
}
- @Test(expected = StringIndexOutOfBoundsException.class)
+ @Test
public void testDeleteCharAtWithNegative() {
- new StrBuilder().deleteCharAt((-1258));
+ assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(() -> {
+ new StrBuilder().deleteCharAt((-1258));
+ });
}
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/StrLookupTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/StrLookupTest.java b/src/test/java/org/apache/commons/text/StrLookupTest.java
index 62330e7..c765b5a 100644
--- a/src/test/java/org/apache/commons/text/StrLookupTest.java
+++ b/src/test/java/org/apache/commons/text/StrLookupTest.java
@@ -16,16 +16,16 @@
*/
package org.apache.commons.text;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.fail;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Test class for {@link StrLookup}.
@@ -50,7 +50,7 @@ public class StrLookupTest {
assertNull(StrLookup.systemPropertiesLookup().lookup("other"));
try {
StrLookup.systemPropertiesLookup().lookup(null);
- fail();
+ fail("Exception expected!");
} catch (final NullPointerException ex) {
// expected
}
@@ -72,7 +72,7 @@ public class StrLookupTest {
newProps.setProperty(osName, newOsName);
System.setProperties(newProps);
try {
- assertEquals("Changed properties not detected", newOsName, sysLookup.lookup(osName));
+ assertEquals(newOsName, sysLookup.lookup(osName), "Changed properties not detected");
} finally {
System.setProperties(oldProperties);
}
@@ -91,7 +91,7 @@ public class StrLookupTest {
final StrLookup<String> sysLookup = StrLookup.systemPropertiesLookup();
System.setProperty(osName, newOsName);
try {
- assertEquals("Changed properties not detected", newOsName, sysLookup.lookup(osName));
+ assertEquals(newOsName, sysLookup.lookup(osName), "Changed properties not detected");
} finally {
System.setProperty(osName, oldOs);
}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/49db4cb3/src/test/java/org/apache/commons/text/StrMatcherTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/commons/text/StrMatcherTest.java b/src/test/java/org/apache/commons/text/StrMatcherTest.java
index 22278f8..f35647f 100644
--- a/src/test/java/org/apache/commons/text/StrMatcherTest.java
+++ b/src/test/java/org/apache/commons/text/StrMatcherTest.java
@@ -18,7 +18,7 @@ package org.apache.commons.text;
import static org.assertj.core.api.Assertions.assertThat;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link StrMatcher}.