]> source.dussan.org Git - poi.git/commitdiff
Update library versions
authorAndreas Beeker <kiwiwings@apache.org>
Tue, 18 Aug 2020 13:50:31 +0000 (13:50 +0000)
committerAndreas Beeker <kiwiwings@apache.org>
Tue, 18 Aug 2020 13:50:31 +0000 (13:50 +0000)
Replace deprecated junit @Rules with assertThrows
Adapt to XMLSec refactoring in version 2.2.0

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1880965 13f79535-47bb-0310-9956-ffa450edef68

38 files changed:
build.xml
src/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java
src/java/org/apache/poi/ss/formula/atp/AnalysisToolPak.java
src/java/org/apache/poi/ss/formula/eval/FunctionEval.java
src/ooxml/java/org/apache/poi/poifs/crypt/dsig/facets/XAdESXLSignatureFacet.java
src/ooxml/testcases/org/apache/poi/extractor/ooxml/TestExtractorFactory.java
src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestContentType.java
src/ooxml/testcases/org/apache/poi/openxml4j/opc/TestPackage.java
src/ooxml/testcases/org/apache/poi/poifs/crypt/dsig/TestSignatureInfo.java
src/ooxml/testcases/org/apache/poi/xslf/usermodel/TestXSLFSlideShowFactory.java
src/ooxml/testcases/org/apache/poi/xssf/streaming/TestSXSSFSheet.java
src/scratchpad/testcases/org/apache/poi/hmef/TestHMEFMessage.java
src/scratchpad/testcases/org/apache/poi/hslf/dev/BasePPTIteratingTest.java
src/scratchpad/testcases/org/apache/poi/hslf/dev/TestPPTXMLDump.java
src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideShowDumper.java
src/scratchpad/testcases/org/apache/poi/hslf/dev/TestSlideShowRecordDumper.java
src/testcases/org/apache/poi/POITestCase.java
src/testcases/org/apache/poi/hpsf/basic/TestWrite.java
src/testcases/org/apache/poi/hssf/dev/BaseTestIteratingXLS.java
src/testcases/org/apache/poi/hssf/dev/TestBiffViewer.java
src/testcases/org/apache/poi/hssf/model/TestSheetAdditional.java
src/testcases/org/apache/poi/hssf/record/TestRecordFactoryInputStream.java
src/testcases/org/apache/poi/hssf/record/aggregates/TestPageSettingsBlock.java
src/testcases/org/apache/poi/hssf/usermodel/TestBugs.java
src/testcases/org/apache/poi/hssf/usermodel/TestHSSFSheet.java
src/testcases/org/apache/poi/poifs/crypt/TestXorEncryption.java
src/testcases/org/apache/poi/poifs/filesystem/TestOfficeXMLException.java
src/testcases/org/apache/poi/poifs/filesystem/TestOle10Native.java
src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSFileSystem.java
src/testcases/org/apache/poi/poifs/filesystem/TestPOIFSStream.java
src/testcases/org/apache/poi/ss/formula/TestFunctionRegistry.java
src/testcases/org/apache/poi/ss/formula/eval/forked/BaseTestForkedEvaluator.java
src/testcases/org/apache/poi/ss/usermodel/BaseTestBugzillaIssues.java
src/testcases/org/apache/poi/ss/usermodel/BaseTestFont.java
src/testcases/org/apache/poi/ss/usermodel/BaseTestSheet.java
src/testcases/org/apache/poi/ss/usermodel/BaseTestWorkbook.java
src/testcases/org/apache/poi/util/TestLittleEndianStreams.java
src/testcases/org/apache/poi/util/TestTempFile.java

index 54537d17fdebfd6aee9232083bad524a23204a22..b95d541ddbf628a05653d6a89935a52138a76589 100644 (file)
--- a/build.xml
+++ b/build.xml
@@ -208,10 +208,20 @@ under the License.
             <loadresource property="versionDir">
                 <string>@{artifact}</string>
                 <filterchain>
-                    <replaceregex pattern="[^:]+:[^:]+:(.*)" replace="\1"/>
+                    <replaceregex pattern="[^:]+:[^:]+:([^:]+).*" replace="\1"/>
                 </filterchain>
             </loadresource>
 
+            <local name="classifier"/>
+            <loadresource property="classifier">
+                <string>@{artifact}</string>
+                <filterchain>
+                    <replaceregex pattern="[^:]+:[^:]+:[^:]+:?([^:]*)" replace="\1"/>
+                    <replaceregex pattern="(.+)" replace="-\1"/>
+                </filterchain>
+            </loadresource>
+            <property name="classifier" value=""/>
+
             <local name="version"/>
             <property name="version" value="${versionDir}" if:blank="@{snapshot}"/>
             <property name="version" value="@{snapshot}"/>
@@ -225,13 +235,23 @@ under the License.
                 </filterchain>
             </loadresource>
 
+            <local name="jarName"/>
+            <property name="jarName" value="${artifactId}-${version}${classifier}.@{packaging}"/>
+
+            <!-- delete old versions -->
+            <delete failonerror="false">
+                <fileset dir="${usageDir}" excludes="${jarName}">
+                    <filename regex="^${artifactId}-[0-9].*${classifier}\.@{packaging}"/>
+                </fileset>
+            </delete>
+
             <local name="jarLoc"/>
             <property name="jarLoc" value="${usageDir}/@{target}" unless:blank="@{target}"/>
-            <property name="jarLoc" value="${usageDir}/${artifactId}-${version}.@{packaging}"/>
+            <property name="jarLoc" value="${usageDir}/${jarName}"/>
 
             <local name="urlLoc"/>
             <property name="urlLoc" value="@{url}" unless:blank="@{url}"/>
-            <property name="urlLoc" value="@{repo}/${groupDir}/${artifactId}/${versionDir}/${artifactId}-${version}.@{packaging}@{query}"/>
+            <property name="urlLoc" value="@{repo}/${groupDir}/${artifactId}/${versionDir}/${jarName}@{query}"/>
 
             <property name="@{prefix}.@{packaging}" value="${jarLoc}"/>
             <property name="@{prefix}.url" value="${urlLoc}"/>
@@ -250,50 +270,50 @@ under the License.
     <dependency prefix="main.com.zaxxer" artifact="com.zaxxer:SparseBitSet:1.2" usage="main"/>
 
     <dependency prefix="main.junit" artifact="junit:junit:4.13" usage="main-tests"/>
-    <dependency prefix="main.jmh" artifact="org.openjdk.jmh:jmh-core:1.19" usage="main-tests"/>
-    <dependency prefix="main.jmhAnnotation" artifact="org.openjdk.jmh:jmh-generator-annprocess:1.19" usage="main-tests"/>
-    <dependency prefix="main.hamcrest" artifact="org.hamcrest:hamcrest-core:1.3" usage="main-tests"/>
-    <dependency prefix="main.xmlunit" artifact="org.xmlunit:xmlunit-core:2.5.1" usage="main-tests"/>
-    <dependency prefix="main.mockito" artifact="org.mockito:mockito-core:3.3.3" usage="main-tests"/>
-    <dependency prefix="main.byte-buddy" artifact="net.bytebuddy:byte-buddy:1.10.1" usage="main-tests"/>
-    <dependency prefix="main.byte-buddy-agent" artifact="net.bytebuddy:byte-buddy-agent:1.10.1" usage="main-tests"/>
-    <dependency prefix="main.objenesis" artifact="org.objenesis:objenesis:2.6" usage="main-tests"/>
+    <dependency prefix="main.jmh" artifact="org.openjdk.jmh:jmh-core:1.25" usage="main-tests"/>
+    <dependency prefix="main.jmhAnnotation" artifact="org.openjdk.jmh:jmh-generator-annprocess:1.25" usage="main-tests"/>
+    <dependency prefix="main.hamcrest" artifact="org.hamcrest:hamcrest:2.2" usage="main-tests"/>
+    <dependency prefix="main.xmlunit" artifact="org.xmlunit:xmlunit-core:2.7.0" usage="main-tests"/>
+    <dependency prefix="main.mockito" artifact="org.mockito:mockito-core:3.5.0" usage="main-tests"/>
+    <dependency prefix="main.byte-buddy" artifact="net.bytebuddy:byte-buddy:1.10.14" usage="main-tests"/>
+    <dependency prefix="main.byte-buddy-agent" artifact="net.bytebuddy:byte-buddy-agent:1.10.14" usage="main-tests"/>
+    <dependency prefix="main.objenesis" artifact="org.objenesis:objenesis:3.1" usage="main-tests"/>
 
     <dependency prefix="main.ant" artifact="org.apache.ant:ant:1.10.8" usage="excelant"/>
     <dependency prefix="main.antlauncher" artifact="org.apache.ant:ant-launcher:1.10.8" usage="excelant"/>
 
     <!-- xml signature libs - not part of the distribution -->
-    <dependency prefix="dsig.xmlsec" artifact="org.apache.santuario:xmlsec:2.1.5" usage="ooxml-provided"/>
+    <dependency prefix="dsig.xmlsec" artifact="org.apache.santuario:xmlsec:2.2.0" usage="ooxml-provided"/>
     <dependency prefix="dsig.bouncycastle-prov" artifact="org.bouncycastle:bcprov-ext-jdk15on:1.66" usage="ooxml-provided"/>
     <dependency prefix="dsig.bouncycastle-pkix" artifact="org.bouncycastle:bcpkix-jdk15on:1.66" usage="ooxml-provided"/>
     <dependency prefix="dsig.slf4j-api" artifact="org.slf4j:slf4j-api:1.7.30" usage="ooxml-provided"/>
+    <!-- only used for signing the release - not used with the ooxml signatures -->
+    <dependency prefix="dsig.bouncycastle-bcpg" artifact="org.bouncycastle:bcpg-jdk15on:1.66" usage="util"/>
 
     <!-- svg/batik libs - not part of the distribution -->
     <dependency prefix="svg.xml-apis-ext" artifact="xml-apis:xml-apis-ext:1.3.04" usage="ooxml-provided"/>
-    <dependency prefix="svg.xmlgraphics-commons" artifact="org.apache.xmlgraphics:xmlgraphics-commons:2.3" usage="ooxml-provided"/>
-    <dependency prefix="svg.batik-all" artifact="org.apache.xmlgraphics:batik-all:1.12" usage="ooxml-provided"/>
+    <dependency prefix="svg.xmlgraphics-commons" artifact="org.apache.xmlgraphics:xmlgraphics-commons:2.4" usage="ooxml-provided"/>
+    <dependency prefix="svg.batik-all" artifact="org.apache.xmlgraphics:batik-all:1.13" usage="ooxml-provided"/>
 
     <!-- jars in the ooxml-lib directory, see the fetch-ooxml-jars target-->
     <dependency prefix="ooxml.curvesapi" artifact="com.github.virtuald:curvesapi:1.06" usage="ooxml"/>
     <dependency prefix="ooxml.xmlbeans" artifact="org.apache.xmlbeans:xmlbeans:4.0.0" usage="ooxml"
                 url="https://ci-builds.apache.org/job/POI/job/POI-XMLBeans-DSL-1.8/lastSuccessfulBuild/artifact/build//xmlbeans-4.0.0.jar"/>
     <dependency prefix="ooxml.commons-compress" artifact="org.apache.commons:commons-compress:1.20" usage="ooxml"/>
-    <!-- only used for compiling xmlbeans schemas -->
-<!--    <dependency prefix="ooxml.commons-compress" artifact="com.github.javaparser:javaparser-core:3.16.1" usage="ooxml-provided"/>-->
 
     <!-- jars in the ooxml-test-lib directory, see the fetch-ooxml-jars target-->
-    <dependency prefix="ooxml.test.reflections" artifact="org.reflections:reflections:0.9.11" usage="ooxml-tests"/>
+    <dependency prefix="ooxml.test.reflections" artifact="org.reflections:reflections:0.9.12" usage="ooxml-tests"/>
     <dependency prefix="ooxml.test.guava" artifact="com.google.guava:guava:29.0-jre" usage="ooxml-tests"/>
-    <dependency prefix="ooxml.test.javassist" artifact="org.javassist:javassist:3.21.0-GA" usage="ooxml-tests"/>
+    <dependency prefix="ooxml.test.javassist" artifact="org.javassist:javassist:3.27.0-GA" usage="ooxml-tests"/>
 
     <!-- coverage libs -->
     <dependency prefix="jacoco" artifact="org.jacoco:jacoco:0.8.5" usage="util" packaging="zip"/>
-    <dependency prefix="asm" artifact="org.ow2.asm:asm:8.0.1" usage="util"/>
-    <dependency prefix="asm-commons" artifact="org.ow2.asm:asm-commons:8.0.1" usage="util"/>
-    <dependency prefix="asm-tree" artifact="org.ow2.asm:asm-tree:8.0.1" usage="util"/>
+    <dependency prefix="asm" artifact="org.ow2.asm:asm:9.0-beta" usage="util"/>
+    <dependency prefix="asm-commons" artifact="org.ow2.asm:asm-commons:9.0-beta" usage="util"/>
+    <dependency prefix="asm-tree" artifact="org.ow2.asm:asm-tree:9.0-beta" usage="util"/>
 
     <!-- license and api checks -->
-    <dependency prefix="rat" artifact="org.apache.rat:apache-rat:0.12" usage="util"/>
+    <dependency prefix="rat" artifact="org.apache.rat:apache-rat:0.13" usage="util"/>
     <dependency prefix="forbidden" artifact="de.thetaphi:forbiddenapis:3.0.1" usage="util"/>
 
     <property name="maven.ooxml.xsds.version.id" value="1.5"/>
@@ -332,23 +352,30 @@ under the License.
     <property name="halt.on.test.failure" value="true"/>
 
     <!-- helper jars for pgp signing, building and nexus staging -->
-    <dependency prefix="dist.bouncycastle-prov" artifact="org.bouncycastle:bcprov-ext-jdk15on:1.65" usage="util"/>
-    <dependency prefix="dist.bouncycastle-prov" artifact="org.bouncycastle:bcpg-jdk15on:1.65" usage="util"/>
     <dependency prefix="dist.commons-openpgp" artifact="org.apache.commons:commons-openpgp:1.0-SNAPSHOT" usage="util"
         repo="https://repository.apache.org/content/groups/snapshots" snapshot="1.0-20190121.221905-12"/>
-    <dependency prefix="dist.nexus-staging" artifact="org.sonatype.nexus.ant:nexus-staging-ant-tasks:1.6.3-uber" usage="util"/>
+    <dependency prefix="dist.nexus-staging" artifact="org.sonatype.nexus.ant:nexus-staging-ant-tasks:1.6.3:uber" usage="util"/>
 
     <!-- jars required for maven helper targets -->
     <dependency prefix="maven.ant" artifact="org.apache.maven:maven-ant-tasks:2.1.3" usage="util"/>
+
+    <!-- subclipse.tigris.org is gone - left-over is hosted at https://bintray.com/openmeetings/maven/org.tigris.subclipse.svnant -->
+    <!-- request will be forwarded to d29vzk4ow07wi7.cloudfront.net which is an Atlassian Marketplace instance -->
     <dependency prefix="dist.svnant" artifact="org.tigris.subclipse:svnant:1.3.1" usage="util"
         repo="https://dl.bintray.com/openmeetings/maven"/>
-    <dependency prefix="dist.svnclient" artifact="org.tigris.subclipse:svnclientadapter:1.3.1" usage="util"
-        repo="https://dl.bintray.com/openmeetings/maven"/>
-    <dependency prefix="dist.svnkit" artifact="org.tmatesoft.svnkit:svnkit:1.8.11" usage="util"/>
-    <dependency prefix="dist.svnkit-javahl16" artifact="org.tmatesoft.svnkit:svnkit-javahl16:1.8.11" usage="util"/>
-    <dependency prefix="dist.sqljet" artifact="org.tmatesoft.sqljet:sqljet:1.1.10" usage="util"/>
+
+    <!-- hosted at https://bintray.com/subclipse/maven/svnclientadapter - https://github.com/subclipse/svnclientadapter -->
+    <dependency prefix="dist.svnclientadapter-base" artifact="org.tigris.svnclientadapter:adapter-base:1.12.0" usage="util"
+        repo="https://dl.bintray.com/subclipse/maven"/>
+    <dependency prefix="dist.svnclientadapter-svnkit" artifact="org.tigris.svnclientadapter:adapter-svnkit:1.12.0" usage="util"
+        repo="https://dl.bintray.com/subclipse/maven"/>
+    <dependency prefix="dist.svnclientadapter-javahl" artifact="org.tigris.svnclientadapter:adapter-javahl:1.12.0" usage="util"
+        repo="https://dl.bintray.com/subclipse/maven"/>
+    <dependency prefix="dist.svnkit" artifact="org.tmatesoft.svnkit:svnkit:1.10.1" usage="util"/>
+    <dependency prefix="dist.svnkit-javahl16" artifact="org.tmatesoft.svnkit:svnkit-javahl16:1.10.1" usage="util"/>
+    <dependency prefix="dist.sqljet" artifact="org.tmatesoft.sqljet:sqljet:1.1.13" usage="util"/>
     <dependency prefix="dist.antlr" artifact="org.antlr:antlr-runtime:3.5.2" usage="util"/>
-    <dependency prefix="dist.sequence-library" artifact="de.regnis.q.sequence:sequence-library:1.0.3" usage="util"/>
+    <dependency prefix="dist.sequence-library" artifact="de.regnis.q.sequence:sequence-library:1.0.4" usage="util"/>
 
 
     <propertyset id="junit.properties">
@@ -560,29 +587,9 @@ under the License.
         <delete dir="compile-lib" failonerror="false"/>
         <delete dir="ooxml-lib" failonerror="false"/>
         <delete dir="ooxml-testlib" failonerror="false"/>
-
-        <delete verbose="true" failonerror="false">
-            <fileset dir="${basedir}/lib" includes="*.jar"/>
-            <fileset dir="${basedir}/lib/main-tests">
-                <include name="mockito-core-3.2.4.jar"/>
-            </fileset>
-            <fileset dir="${basedir}/lib/ooxml">
-                <include name="xmlbeans-3.1.0.jar"/>
-            </fileset>
-            <fileset dir="${basedir}/lib/ooxml-provided">
-                <include name="bcpkix-jdk15on-1.65.jar"/>
-                <include name="bcprov-ext-jdk15on-1.65.jar"/>
-            </fileset>
-            <fileset dir="${basedir}/lib/ooxml-tests">
-                <include name="guava-20.0.jar"/>
-            </fileset>
-            <fileset dir="${basedir}/lib/util">
-                <include name="asm*7.2.jar"/>
-                <include name="forbiddenapis-2.6.jar"/>
-            </fileset>
-            <fileset dir="${basedir}/lib/excelant">
-                <include name="ant*1.10.1.jar"/>
-            </fileset>
+        <delete dir="${basedir}/lib" includes="*.jar" failonerror="false"/>
+        <delete>
+            <fileset dir="lib/main-tests" includes="hamcrest-core*"/>
         </delete>
 
         <condition property="jars.present">
@@ -694,12 +701,15 @@ under the License.
         <downloadfile src="${svg.xml-apis-ext.url}" dest="${svg.xml-apis-ext.jar}"/>
         <downloadfile src="${svg.xmlgraphics-commons.url}" dest="${svg.xmlgraphics-commons.jar}"/>
     </target>
+
     <target name="check-svn-jars">
         <condition property="svn.jars.present">
             <or>
                 <and>
                     <available file="${dist.svnant.jar}"/>
-                    <available file="${dist.svnclient.jar}"/>
+                    <available file="${dist.svnclientadapter-base.jar}"/>
+                    <available file="${dist.svnclientadapter-svnkit.jar}"/>
+                    <available file="${dist.svnclientadapter-javahl.jar}"/>
                     <available file="${dist.svnkit.jar}"/>
                     <available file="${dist.svnkit-javahl16.jar}"/>
                     <available file="${dist.sqljet.jar}"/>
@@ -712,7 +722,9 @@ under the License.
     </target>
     <target name="fetch-svn-jars" depends="check-svn-jars" unless="svn.jars.present">
         <downloadfile src="${dist.svnant.url}" dest="${dist.svnant.jar}"/>
-        <downloadfile src="${dist.svnclient.url}" dest="${dist.svnclient.jar}"/>
+        <downloadfile src="${dist.svnclientadapter-base.url}" dest="${dist.svnclientadapter-base.jar}"/>
+        <downloadfile src="${dist.svnclientadapter-svnkit.url}" dest="${dist.svnclientadapter-svnkit.jar}"/>
+        <downloadfile src="${dist.svnclientadapter-javahl.url}" dest="${dist.svnclientadapter-javahl.jar}"/>
         <downloadfile src="${dist.svnkit.url}" dest="${dist.svnkit.jar}"/>
         <downloadfile src="${dist.svnkit-javahl16.url}" dest="${dist.svnkit-javahl16.jar}"/>
         <downloadfile src="${dist.sqljet.url}" dest="${dist.sqljet.jar}"/>
@@ -2475,15 +2487,14 @@ under the License.
 
         <fixcrlf srcDir="${dist.dir}" includes="**/*.md5,**/*.sha1,**/*.sha256,**/*.sha512" eol="unix"/>
 
-        <downloadfile src="${dist.bouncycastle-prov.url}" dest="${dist.bouncycastle-prov.jar}"/>
-        <downloadfile src="${dist.bouncycastle-bcpg.url}" dest="${dist.bouncycastle-bcpg.jar}"/>
+        <downloadfile src="${dsig.bouncycastle-bcpg.url}" dest="${dsig.bouncycastle-bcpg.jar}"/>
         <downloadfile src="${dist.commons-openpgp.url}" dest="${dist.commons-openpgp.jar}"/>
 
         <taskdef resource="org/apache/commons/openpgp/ant/antlib.xml" uri="antlib:org.apache.commons.openpgp.ant">
             <classpath>
                 <pathelement path="${dist.commons-openpgp.jar}"/>
-                <pathelement path="${dist.bouncycastle-prov.jar}"/>
-                <pathelement path="${dist.bouncycastle-bcpg.jar}"/>
+                <pathelement path="${dsig.bouncycastle-prov.jar}"/>
+                <pathelement path="${dsig.bouncycastle-bcpg.jar}"/>
             </classpath>
         </taskdef>
 
@@ -2592,7 +2603,9 @@ under the License.
 
         <path id="path.svnant">
             <pathelement location="${dist.svnant.jar}"/>
-            <pathelement location="${dist.svnclient.jar}"/>
+            <pathelement location="${dist.svnclientadapter-base.jar}"/>
+            <pathelement location="${dist.svnclientadapter-svnkit.jar}"/>
+            <pathelement location="${dist.svnclientadapter-javahl.jar}"/>
             <pathelement location="${dist.svnkit.jar}"/>
             <pathelement location="${dist.svnkit-javahl16.jar}"/>
             <pathelement location="${dist.sqljet.jar}"/>
index 7f9692ecdc834518a7e43a974a209a579f8806ee..9fd9b96bd6bba0902bfc5a6158832c6f7821cad3 100644 (file)
@@ -119,6 +119,7 @@ import org.apache.poi.util.LittleEndianByteArrayInputStream;
 import org.apache.poi.util.LittleEndianByteArrayOutputStream;
 import org.apache.poi.util.POILogFactory;
 import org.apache.poi.util.POILogger;
+import org.apache.poi.util.Removal;
 
 /**
  * High level representation of a workbook.  This is the first object most users
@@ -1151,7 +1152,7 @@ public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss
     public HSSFFont createFont() {
         /*FontRecord font =*/
         workbook.createNewFont();
-        int fontindex = getNumberOfFontsAsInt() - 1;
+        int fontindex = getNumberOfFonts() - 1;
 
         if (fontindex > 3) {
             fontindex++;   // THERE IS NO FOUR!!
@@ -1172,7 +1173,7 @@ public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss
     public HSSFFont findFont(boolean bold, short color, short fontHeight,
                              String name, boolean italic, boolean strikeout,
                              short typeOffset, byte underline) {
-        int numberOfFonts = getNumberOfFontsAsInt();
+        int numberOfFonts = getNumberOfFonts();
         for (int i = 0; i <= numberOfFonts; i++) {
             // Remember - there is no 4!
             if (i == 4) {
@@ -1202,6 +1203,7 @@ public final class HSSFWorkbook extends POIDocument implements org.apache.poi.ss
 
     @Override
     @Deprecated
+    @Removal(version="6.0.0")
     public int getNumberOfFontsAsInt() {
         return getNumberOfFonts();
     }
index 5f312744396d5bc12ea724035eeb01fc55218b5f..076eafd03c2fb18d4811645cbbb9a2e24fd84d2a 100644 (file)
@@ -260,7 +260,7 @@ public final class AnalysisToolPak implements UDFFinder {
         }
         FreeRefFunction f = inst.findFunction(name);
         if(f != null && !(f instanceof NotImplemented)) {
-            throw new IllegalArgumentException("POI already implememts " + name +
+            throw new IllegalArgumentException("POI already implements " + name +
                     ". You cannot override POI's implementations of Excel functions");
         }
 
index ad034e1a67a63eb6fa6ce88f9dd848f258e6dd95..da670439a9d9356c101561a1051f200cf869aa5f 100644 (file)
@@ -189,7 +189,7 @@ public final class FunctionEval {
         retval[FunctionID.INDIRECT] = null; // Indirect.evaluate has different signature
 
         retval[162] = TextFunction.CLEAN;
-        
+
         retval[163] = MatrixFunction.MDETERM;
         retval[164] = MatrixFunction.MINVERSE;
         retval[165] = MatrixFunction.MMULT;
@@ -394,7 +394,7 @@ public final class FunctionEval {
         if(functions[idx] instanceof NotImplementedFunction) {
             functions[idx] = func;
         } else {
-            throw new IllegalArgumentException("POI already implememts " + name +
+            throw new IllegalArgumentException("POI already implements " + name +
                     ". You cannot override POI's implementations of Excel functions");
         }
     }
index 60b9e26e67621d83325de04987ecaa87708baa24..5e1ee2fbe4d32b191382a27efbdb68759723d545 100644 (file)
@@ -299,7 +299,7 @@ public class XAdESXLSignatureFacet implements SignatureFacet {
                  * and will be missing from the c14n resulting nodes.
                  */
                 Canonicalizer c14n = Canonicalizer.getInstance(c14nAlgoId);
-                c14nValue.write(c14n.canonicalizeSubtree(node));
+                c14n.canonicalizeSubtree(node, c14nValue);
             }
         } catch (RuntimeException e) {
             throw e;
index 3e570e2b51ddee865c1939f7fd8427caf2348fc2..1a4940c0511ecb0c9301799328b68b27eda967fb 100644 (file)
@@ -21,6 +21,7 @@ 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.assertThrows;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
@@ -42,14 +43,11 @@ import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
 import org.apache.poi.openxml4j.opc.OPCPackage;
 import org.apache.poi.openxml4j.opc.PackageAccess;
 import org.apache.poi.poifs.filesystem.FileMagic;
-import org.apache.poi.poifs.filesystem.NotOLE2FileException;
 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 import org.apache.poi.xssf.extractor.XSSFEventBasedExcelExtractor;
 import org.apache.poi.xssf.extractor.XSSFExcelExtractor;
 import org.apache.xmlbeans.XmlException;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 
 /**
  * Test that the extractor factory plays nicely
@@ -129,9 +127,6 @@ public class TestExtractorFactory {
         R apply(T t) throws IOException, OpenXML4JException, XmlException;
     }
 
-    @Rule
-    public ExpectedException thrown = ExpectedException.none();
-
     @Test
     public void testFile() throws Exception {
         for (int i = 0; i < TEST_SET.length; i += 4) {
@@ -142,11 +137,12 @@ public class TestExtractorFactory {
     }
 
     @Test
-    public void testFileInvalid() throws Exception {
-        thrown.expectMessage("Can't create extractor - unsupported file type: UNKNOWN");
-        thrown.expect(IOException.class);
-        // Text
-        ExtractorFactory.createExtractor(txt);
+    public void testFileInvalid() {
+        IOException ex = assertThrows(
+            IOException.class,
+            () -> ExtractorFactory.createExtractor(txt)
+        );
+        assertEquals("Can't create extractor - unsupported file type: UNKNOWN", ex.getMessage());
     }
 
     @Test
@@ -155,10 +151,11 @@ public class TestExtractorFactory {
     }
 
     @Test
-    public void testInputStreamInvalid() throws Exception {
-        thrown.expectMessage("Can't create extractor - unsupported file type: UNKNOWN");
-        thrown.expect(IOException.class);
-        testInvalid(ExtractorFactory::createExtractor);
+    public void testInputStreamInvalid() throws IOException {
+        try (FileInputStream fis = new FileInputStream(txt)) {
+            IOException ex = assertThrows(IOException.class, () -> ExtractorFactory.createExtractor(fis));
+            assertTrue(ex.getMessage().contains(FileMagic.UNKNOWN.name()));
+        }
     }
 
     @Test
@@ -167,10 +164,12 @@ public class TestExtractorFactory {
     }
 
     @Test
-    public void testPOIFSInvalid() throws Exception {
-        thrown.expectMessage("Invalid header signature; read 0x3D20726F68747541, expected 0xE11AB1A1E011CFD0");
-        thrown.expect(NotOLE2FileException.class);
-        testInvalid((f) -> ExtractorFactory.createExtractor(new POIFSFileSystem(f)));
+    public void testPOIFSInvalid() {
+        IOException ex = assertThrows(
+            IOException.class,
+            () -> ExtractorFactory.createExtractor(new POIFSFileSystem(txt))
+        );
+        assertTrue(ex.getMessage().contains("Invalid header signature; read 0x3D20726F68747541, expected 0xE11AB1A1E011CFD0"));
     }
 
     private void testStream(final FunctionEx<FileInputStream, POITextExtractor> poifsIS, final boolean loadOOXML)
@@ -199,17 +198,6 @@ public class TestExtractorFactory {
         }
     }
 
-    private void testInvalid(FunctionEx<FileInputStream, POITextExtractor> poifs) throws IOException, OpenXML4JException, XmlException {
-        // Text
-        try (FileInputStream fis = new FileInputStream(txt);
-             POITextExtractor ignored = poifs.apply(fis)) {
-            fail("extracting from invalid package");
-        } catch (IllegalArgumentException e) {
-            assertTrue("Had: " + e, e.getMessage().contains(FileMagic.UNKNOWN.name()));
-            throw e;
-        }
-    }
-
     @Test
     public void testPackage() throws Exception {
         for (int i = 0; i < TEST_SET.length; i += 4) {
@@ -273,6 +261,7 @@ public class TestExtractorFactory {
             }
 
             try (POITextExtractor extractor = xmlFactory.create(OPCPackage.open(xlsx.toString(), PackageAccess.READ))) {
+                assertNotNull(extractor);
                 assertTrue(extractor.getText().length() > 200);
             }
         } finally {
@@ -296,6 +285,7 @@ public class TestExtractorFactory {
             assertTrue(extractor instanceof XSSFExcelExtractor);
         }
         try (POITextExtractor extractor = xmlFactory.create(OPCPackage.open(xlsx.toString()))) {
+            assertNotNull(extractor);
             assertTrue(extractor.getText().length() > 200);
         }
     }
index 3858bc688da94093486a3447082e85b8d490d70f..4995fcb2ef18c0c8a7c24402c98f2cb727f9215e 100644 (file)
@@ -19,6 +19,7 @@ package org.apache.poi.openxml4j.opc;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThrows;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
@@ -29,9 +30,7 @@ import javax.xml.parsers.DocumentBuilderFactory;
 import org.apache.poi.openxml4j.OpenXML4JTestDataSamples;
 import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
 import org.apache.poi.openxml4j.opc.internal.ContentType;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 
 /**
  * Tests for content type (ContentType class).
@@ -40,9 +39,6 @@ public final class TestContentType {
 
     private static final String FEATURE_DISALLOW_DOCTYPE_DECL = "http://apache.org/xml/features/disallow-doctype-decl";
 
-    @Rule
-    public ExpectedException exception = ExpectedException.none();
-
     /**
      * Check rule M1.13: Package implementers shall only create and only
      * recognize parts with a content type; format designers shall specify a
@@ -158,12 +154,13 @@ public final class TestContentType {
      */
     @Test
     public void testFileWithContentTypeEntities() throws Exception {
-        if (!isOldXercesActive()) {
-            exception.expect(InvalidFormatException.class);
+        try (InputStream is = OpenXML4JTestDataSamples.openSampleStream("ContentTypeHasEntities.ooxml")) {
+            if (isOldXercesActive()) {
+                OPCPackage.open(is);
+            } else {
+                assertThrows(InvalidFormatException.class, () -> OPCPackage.open(is));
+            }
         }
-
-        InputStream is = OpenXML4JTestDataSamples.openSampleStream("ContentTypeHasEntities.ooxml");
-        OPCPackage.open(is);
     }
 
     /**
index d8fc1b7b849db447ac4c9914ca36bdc8bec66e72..5f95abd1ca98847042eb7368620597e731ba72ac 100644 (file)
@@ -22,11 +22,11 @@ import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getSampleFile;
 import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.getSampleFileName;
 import static org.apache.poi.openxml4j.OpenXML4JTestDataSamples.openSampleStream;
 import static org.apache.poi.openxml4j.opc.PackagingURIHelper.createPartName;
-import static org.hamcrest.core.StringContains.containsString;
 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.assertThrows;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
@@ -50,6 +50,7 @@ import java.util.List;
 import java.util.TreeMap;
 import java.util.function.BiConsumer;
 import java.util.regex.Pattern;
+import java.util.stream.Stream;
 
 import com.google.common.hash.Hashing;
 import com.google.common.io.Files;
@@ -88,13 +89,9 @@ import org.apache.poi.xssf.usermodel.XSSFRelation;
 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 import org.apache.poi.xwpf.usermodel.XWPFRelation;
 import org.apache.xmlbeans.XmlException;
-import org.hamcrest.Description;
-import org.hamcrest.TypeSafeMatcher;
-import org.hamcrest.core.AllOf;
 import org.junit.Ignore;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.function.ThrowingRunnable;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.NodeList;
@@ -107,9 +104,6 @@ public final class TestPackage {
        private static final String CONTENT_EXT_PROPS = "application/vnd.openxmlformats-officedocument.extended-properties+xml";
        private static final POIDataSamples xlsSamples = POIDataSamples.getSpreadSheetInstance();
 
-       @Rule
-       public ExpectedException expectedEx = ExpectedException.none();
-
        /**
         * Test that just opening and closing the file doesn't alter the document.
         */
@@ -645,115 +639,46 @@ public final class TestPackage {
                }
     }
 
-
-       @Test
-       public void NonOOXML_OLE2Stream() throws Exception {
-       expectedEx.expect(OLE2NotOfficeXmlFileException.class);
-       expectedEx.expectMessage(AllOf.allOf(
-                       containsString("The supplied data appears to be in the OLE2 Format"),
-                       containsString("You are calling the part of POI that deals with OOXML")
-               ));
-               try (InputStream stream = xlsSamples.openResourceAsStream("SampleSS.xls");
-                        OPCPackage p = OPCPackage.open(stream)) {
-                       assertNotNull(p);
-                       fail("Shouldn't be able to open OLE2");
-               }
-       }
-
        @Test
-       public void NonOOXML_OLE2File() throws Exception {
-               expectedEx.expect(OLE2NotOfficeXmlFileException.class);
-               expectedEx.expectMessage(AllOf.allOf(
-                       containsString("The supplied data appears to be in the OLE2 Format"),
-                       containsString("You are calling the part of POI that deals with OOXML")
-               ));
-               try (OPCPackage p = OPCPackage.open(xlsSamples.getFile("SampleSS.xls"))) {
-                       assertNotNull(p);
-                       fail("Shouldn't be able to open OLE2");
-               }
-       }
-
-       @Test
-       public void NonOOXML_RawXmlStream() throws Exception {
-               expectedEx.expect(NotOfficeXmlFileException.class);
-               expectedEx.expectMessage(AllOf.allOf(
-                       containsString("The supplied data appears to be a raw XML file"),
-                       containsString("Formats such as Office 2003 XML")
-               ));
-               try (InputStream stream = xlsSamples.openResourceAsStream("SampleSS.xml");
-                        OPCPackage p = OPCPackage.open(stream)) {
-                       assertNotNull(p);
-                       fail("Shouldn't be able to open XML");
-               }
-       }
-
-       @Test
-       public void NonOOXML_RawXmlFile() throws Exception {
-               expectedEx.expect(NotOfficeXmlFileException.class);
-               expectedEx.expectMessage(AllOf.allOf(
-                       containsString("The supplied data appears to be a raw XML file"),
-                       containsString("Formats such as Office 2003 XML")
-               ));
-               try (OPCPackage p = OPCPackage.open(xlsSamples.getFile("SampleSS.xml"))) {
-                       assertNotNull(p);
-                       fail("Shouldn't be able to open XML");
-               }
-       }
-
-       @Test
-       public void NonOOXML_ODFStream() throws Exception {
-               expectedEx.expect(ODFNotOfficeXmlFileException.class);
-               expectedEx.expectMessage(AllOf.allOf(
-                       containsString("The supplied data appears to be in ODF"),
-                       containsString("Formats like these (eg ODS")
-               ));
-               try (InputStream stream = xlsSamples.openResourceAsStream("SampleSS.ods");
-                        OPCPackage p = OPCPackage.open(stream)) {
-                       assertNotNull(p);
-                       fail("Shouldn't be able to open ODS");
-               }
-       }
-
-       @Test
-       public void NonOOXML_ODFFile() throws Exception {
-               expectedEx.expect(ODFNotOfficeXmlFileException.class);
-               expectedEx.expectMessage(AllOf.allOf(
-                       containsString("The supplied data appears to be in ODF"),
-                       containsString("Formats like these (eg ODS")
-               ));
-               try (OPCPackage p = OPCPackage.open(xlsSamples.getFile("SampleSS.ods"))) {
-                       assertNotNull(p);
-                       fail("Shouldn't be able to open ODS");
-               }
+       public void NonOOXML_File() throws Exception {
+       handleNonOOXML(
+                       "SampleSS.xls", OLE2NotOfficeXmlFileException.class,
+                       "The supplied data appears to be in the OLE2 Format",
+                       "You are calling the part of POI that deals with OOXML"
+               );
+
+       handleNonOOXML(
+                       "SampleSS.xml", NotOfficeXmlFileException.class,
+                       "The supplied data appears to be a raw XML file",
+                       "Formats such as Office 2003 XML"
+               );
+
+       handleNonOOXML(
+                       "SampleSS.ods", ODFNotOfficeXmlFileException.class,
+                       "The supplied data appears to be in ODF",
+                       "Formats like these (eg ODS"
+               );
+
+       handleNonOOXML(
+                       "SampleSS.txt", NotOfficeXmlFileException.class,
+                       "No valid entries or contents found",
+                       "not a valid OOXML"
+               );
        }
 
-       @Test
-       public void NonOOXML_TextStream() throws Exception {
-               expectedEx.expect(NotOfficeXmlFileException.class);
-               expectedEx.expectMessage(AllOf.allOf(
-                               containsString("No valid entries or contents found"),
-                               containsString("not a valid OOXML")
-               ));
-               try (InputStream stream = xlsSamples.openResourceAsStream("SampleSS.txt");
-                        OPCPackage p = OPCPackage.open(stream)) {
-                       assertNotNull(p);
-                       fail("Shouldn't be able to open Plain Text");
+       private void handleNonOOXML(String file, Class<? extends UnsupportedFileFormatException> exception, String... messageParts) throws IOException {
+               try (InputStream stream = xlsSamples.openResourceAsStream(file)) {
+                       ThrowingRunnable[] trs = {
+                               () -> OPCPackage.open(stream),
+                               () -> OPCPackage.open(xlsSamples.getFile(file))
+                       };
+                       for (ThrowingRunnable tr : trs) {
+                               Exception ex = assertThrows("Shouldn't be able to open "+file, exception, tr);
+                               Stream.of(messageParts).forEach(mp -> assertTrue(ex.getMessage().contains(mp)));
+                       }
                }
        }
 
-       @Test
-       public void NonOOXML_TextFile() throws Exception {
-               // Unhelpful low-level error, sorry
-               expectedEx.expect(UnsupportedFileFormatException.class);
-               expectedEx.expectMessage(AllOf.allOf(
-                               containsString("No valid entries or contents found"),
-                               containsString("not a valid OOXML")
-               ));
-               try (OPCPackage p = OPCPackage.open(xlsSamples.getFile("SampleSS.txt"))) {
-                       assertNotNull(p);
-                       fail("Shouldn't be able to open Plain Text");
-               }
-       }
 
        /**
         * Zip bomb handling test
@@ -805,29 +730,32 @@ public final class TestPackage {
                        }
                }
 
-               expectedEx.expect(IOException.class);
-               expectedEx.expectMessage("Zip bomb detected!");
-
-               try (Workbook wb = WorkbookFactory.create(new ByteArrayInputStream(bos.toByteArray()))) {
-                       wb.getSheetAt(0);
-               }
+               IOException ex = assertThrows(
+                       IOException.class,
+                       () -> WorkbookFactory.create(new ByteArrayInputStream(bos.toByteArray()))
+               );
+        assertTrue(ex.getMessage().contains("Zip bomb detected!"));
     }
 
        @Test
-       public void testZipEntityExpansionTerminates() throws IOException, OpenXML4JException, XmlException {
-               expectedEx.expect(IllegalStateException.class);
-               expectedEx.expectMessage("The text would exceed the max allowed overall size of extracted text.");
-               openXmlBombFile("poc-shared-strings.xlsx");
+       public void testZipEntityExpansionTerminates() {
+               IllegalStateException ex = assertThrows(
+                       IllegalStateException.class,
+                       () -> openXmlBombFile("poc-shared-strings.xlsx")
+               );
+               assertTrue(ex.getMessage().contains("The text would exceed the max allowed overall size of extracted text."));
        }
 
        @Test
-       public void testZipEntityExpansionSharedStringTableEvents() throws IOException, OpenXML4JException, XmlException {
+       public void testZipEntityExpansionSharedStringTableEvents() {
                boolean before = ExtractorFactory.getThreadPrefersEventExtractors();
                ExtractorFactory.setThreadPrefersEventExtractors(true);
                try {
-                       expectedEx.expect(IllegalStateException.class);
-                       expectedEx.expectMessage("The text would exceed the max allowed overall size of extracted text.");
-                       openXmlBombFile("poc-shared-strings.xlsx");
+                       IllegalStateException ex = assertThrows(
+                               IllegalStateException.class,
+                               () -> openXmlBombFile("poc-shared-strings.xlsx")
+                       );
+                       assertTrue(ex.getMessage().contains("The text would exceed the max allowed overall size of extracted text."));
                } finally {
                        ExtractorFactory.setThreadPrefersEventExtractors(before);
                }
@@ -835,19 +763,33 @@ public final class TestPackage {
 
 
        @Test
-       public void testZipEntityExpansionExceedsMemory() throws IOException, OpenXML4JException, XmlException {
-               expectedEx.expect(IOException.class);
-               expectedEx.expectMessage("unable to parse shared strings table");
-               expectedEx.expectCause(getCauseMatcher(SAXParseException.class, "The parser has encountered more than"));
-               openXmlBombFile("poc-xmlbomb.xlsx");
+       public void testZipEntityExpansionExceedsMemory() {
+               IOException ex = assertThrows(
+                       IOException.class,
+                       () -> openXmlBombFile("poc-xmlbomb.xlsx")
+               );
+               assertTrue(ex.getMessage().contains("unable to parse shared strings table"));
+               assertTrue(matchSAXEx(ex));
        }
 
        @Test
-       public void testZipEntityExpansionExceedsMemory2() throws IOException, OpenXML4JException, XmlException {
-               expectedEx.expect(IOException.class);
-               expectedEx.expectMessage("unable to parse shared strings table");
-               expectedEx.expectCause(getCauseMatcher(SAXParseException.class, "The parser has encountered more than"));
-       openXmlBombFile("poc-xmlbomb-empty.xlsx");
+       public void testZipEntityExpansionExceedsMemory2() {
+               IOException ex = assertThrows(
+                       IOException.class,
+                       () -> openXmlBombFile("poc-xmlbomb-empty.xlsx")
+               );
+               assertTrue(ex.getMessage().contains("unable to parse shared strings table"));
+               assertTrue(matchSAXEx(ex));
+       }
+
+       private static boolean matchSAXEx(Exception root) {
+               for (Throwable t = root; t != null; t = t.getCause()) {
+                       if (t.getClass().isAssignableFrom(SAXParseException.class) &&
+                               t.getMessage().contains("The parser has encountered more than")) {
+                               return true;
+                       }
+               }
+               return false;
        }
 
        private void openXmlBombFile(String file) throws IOException, OpenXML4JException, XmlException {
@@ -873,24 +815,28 @@ public final class TestPackage {
        }
 
        @Test
-       public void zipBombCheckSizesRatioTooSmall() throws IOException, EncryptedDocumentException {
-               expectedEx.expect(POIXMLException.class);
-               expectedEx.expectMessage("You can adjust this limit via ZipSecureFile.setMinInflateRatio()");
-               getZipStatsAndConsume((max_size, min_ratio) -> {
-                       // check ratio out of bounds
-                       ZipSecureFile.setMinInflateRatio(min_ratio+0.002);
-               });
+       public void zipBombCheckSizesRatioTooSmall() {
+               POIXMLException ex = assertThrows(
+                       POIXMLException.class,
+                       () -> getZipStatsAndConsume((max_size, min_ratio) -> {
+                               // check ratio out of bounds
+                               ZipSecureFile.setMinInflateRatio(min_ratio+0.002);
+                       })
+               );
+               assertTrue(ex.getMessage().contains("You can adjust this limit via ZipSecureFile.setMinInflateRatio()"));
        }
 
        @Test
        public void zipBombCheckSizesSizeTooBig() throws IOException, EncryptedDocumentException {
-               expectedEx.expect(POIXMLException.class);
-               expectedEx.expectMessage("You can adjust this limit via ZipSecureFile.setMaxEntrySize()");
-               getZipStatsAndConsume((max_size, min_ratio) -> {
-                       // check max entry size ouf of bounds
-                       ZipSecureFile.setMinInflateRatio(min_ratio-0.002);
-                       ZipSecureFile.setMaxEntrySize(max_size-200);
-               });
+               POIXMLException ex = assertThrows(
+                       POIXMLException.class,
+                       () -> getZipStatsAndConsume((max_size, min_ratio) -> {
+                               // check max entry size ouf of bounds
+                               ZipSecureFile.setMinInflateRatio(min_ratio-0.002);
+                               ZipSecureFile.setMaxEntrySize(max_size-200);
+                       })
+               );
+               assertTrue(ex.getMessage().contains("You can adjust this limit via ZipSecureFile.setMaxEntrySize()"));
        }
 
        private void getZipStatsAndConsume(BiConsumer<Long,Double> ratioCon) throws IOException {
@@ -1121,42 +1067,6 @@ public final class TestPackage {
                }
        }
 
-       @SuppressWarnings("SameParameterValue")
-       private static <T extends Throwable> AnyCauseMatcher<T> getCauseMatcher(Class<T> cause, String message) {
-       // junit is only using hamcrest-core, so instead of adding hamcrest-beans, we provide the throwable
-               // search with the basics...
-               // see https://stackoverflow.com/a/47703937/2066598
-               return new AnyCauseMatcher<>(cause, message);
-       }
-
-       private static class AnyCauseMatcher<T extends Throwable> extends TypeSafeMatcher<T> {
-               private final Class<T> expectedType;
-               private final String expectedMessage;
-
-               AnyCauseMatcher(Class<T> expectedType, String expectedMessage) {
-                       this.expectedType = expectedType;
-                       this.expectedMessage = expectedMessage;
-               }
-
-               @Override
-               protected boolean matchesSafely(final Throwable root) {
-                       for (Throwable t = root; t != null; t = t.getCause()) {
-                               if (t.getClass().isAssignableFrom(expectedType) && t.getMessage().contains(expectedMessage)) {
-                                       return true;
-                               }
-                       }
-                       return false;
-               }
-
-               @Override
-               public void describeTo(Description description) {
-                       description.appendText("expects type ")
-                                       .appendValue(expectedType)
-                                       .appendText(" and a message ")
-                                       .appendValue(expectedMessage);
-               }
-       }
-
        @SuppressWarnings("UnstableApiUsage")
        @Test
        public void testBug63029() throws Exception {
index a4e977c1481289b0bd021f34ccc90afa79e9ca25..988024907aae88be76b3099d6e20110591b7db92 100644 (file)
@@ -145,9 +145,7 @@ import org.junit.AfterClass;
 import org.junit.Assume;
 import org.junit.BeforeClass;
 import org.junit.Ignore;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 import org.w3.x2000.x09.xmldsig.ReferenceType;
 import org.w3.x2000.x09.xmldsig.SignatureDocument;
 import org.w3c.dom.Document;
@@ -160,9 +158,6 @@ public class TestSignatureInfo {
     private KeyPair keyPair;
     private X509Certificate x509;
 
-    @Rule
-    public ExpectedException thrown = ExpectedException.none();
-
     @AfterClass
     public static void removeUserLocale() {
         LocaleUtil.resetUserLocale();
index b02995fcdd76ecdc90758a0fb6aebd7ad36723cd..b4fb08fef0113dab1d4c5073bc05a3fbb917a8cc 100644 (file)
 
 package org.apache.poi.xslf.usermodel;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
@@ -33,30 +37,25 @@ import org.apache.poi.sl.usermodel.BaseTestSlideShowFactory;
 import org.apache.poi.util.IOUtils;
 import org.apache.poi.util.TempFile;
 import org.junit.Test;
-import org.junit.Rule;
-import org.junit.rules.ExpectedException;
 
 public final class TestXSLFSlideShowFactory extends BaseTestSlideShowFactory {
-    private static POIDataSamples _slTests = POIDataSamples.getSlideShowInstance();
+    private static final POIDataSamples _slTests = POIDataSamples.getSlideShowInstance();
     private static final String filename = "SampleShow.pptx";
     private static final String password = "opensesame";
     private static final String removeExpectedExceptionMsg =
             "This functionality this unit test is trying to test is now passing. " +
             "The unit test needs to be updated by deleting the expected exception code. Status and close any related bugs.";
 
-    @Rule
-    public ExpectedException thrown = ExpectedException.none();
-
     @Test
-    public void testFactoryFromFile() throws Exception {
+    public void testFactoryFromFile() {
         // Remove thrown.* when bug 58779 is resolved
         // In the mean time, this function will modify SampleShow.pptx on disk.
-        thrown.expect(AssertionError.class);
-        // thrown.expectCause(Matcher<ArrayComparisonFailure>);
-        thrown.expectMessage("SampleShow.pptx sample file was modified as a result of closing the slideshow");
-        thrown.reportMissingExceptionWithMessage("Bug 58779: " + removeExpectedExceptionMsg);
-    
-        testFactoryFromFile(filename);
+        AssertionError ex = assertThrows(
+            "Bug 58779: " + removeExpectedExceptionMsg,
+            AssertionError.class,
+            () -> testFactoryFromFile(filename)
+        );
+        assertTrue(ex.getMessage().contains("SampleShow.pptx sample file was modified as a result of closing the slideshow"));
     }
 
     @Test
@@ -65,13 +64,14 @@ public final class TestXSLFSlideShowFactory extends BaseTestSlideShowFactory {
     }
 
     @Test
-    public void testFactoryFromNative() throws Exception {
+    public void testFactoryFromNative()  {
         // Remove thrown.* when unit test for XSLF SlideShowFactory.create(OPCPackage) is implemented
-        thrown.expect(UnsupportedOperationException.class);
-        thrown.expectMessage("Test not implemented");
-        thrown.reportMissingExceptionWithMessage(removeExpectedExceptionMsg);
-
-        testFactoryFromNative(filename);
+        UnsupportedOperationException ex = assertThrows(
+            removeExpectedExceptionMsg,
+            UnsupportedOperationException.class,
+            () -> testFactoryFromNative(filename)
+        );
+        assertEquals("Test not implemented", ex.getMessage());
     }
 
     @Test
index 15dcf326a05aea207f596c8943e39d7eeb3ffb60..8a3ffe433f13569588ab45ac6a35a222dab07736 100644 (file)
@@ -20,6 +20,7 @@
 package org.apache.poi.xssf.streaming;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThrows;
 import static org.junit.Assert.fail;
 
 import java.io.IOException;
@@ -57,18 +58,16 @@ public final class TestSXSSFSheet extends BaseTestXSheet {
      */
     @Override
     @Test
-    public void cloneSheet() throws IOException {
-        thrown.expect(RuntimeException.class);
-        thrown.expectMessage("Not Implemented");
-        super.cloneSheet();
+    public void cloneSheet() {
+        RuntimeException ex = assertThrows(RuntimeException.class, super::cloneSheet);
+        assertEquals("Not Implemented", ex.getMessage());
     }
 
     @Override
     @Test
-    public void cloneSheetMultipleTimes() throws IOException {
-        thrown.expect(RuntimeException.class);
-        thrown.expectMessage("Not Implemented");
-        super.cloneSheetMultipleTimes();
+    public void cloneSheetMultipleTimes() {
+        RuntimeException ex = assertThrows(RuntimeException.class, super::cloneSheetMultipleTimes);
+        assertEquals("Not Implemented", ex.getMessage());
     }
 
     /**
@@ -76,10 +75,9 @@ public final class TestSXSSFSheet extends BaseTestXSheet {
      */
     @Override
     @Test
-    public void shiftMerged() throws IOException {
-        thrown.expect(RuntimeException.class);
-        thrown.expectMessage("Not Implemented");
-        super.shiftMerged();
+    public void shiftMerged() {
+        RuntimeException ex = assertThrows(RuntimeException.class, super::shiftMerged);
+        assertEquals("Not Implemented", ex.getMessage());
     }
 
     /**
@@ -89,15 +87,14 @@ public final class TestSXSSFSheet extends BaseTestXSheet {
      */
     @Override
     @Test
-    public void bug35084() throws IOException {
-        thrown.expect(RuntimeException.class);
-        thrown.expectMessage("Not Implemented");
-        super.bug35084();
+    public void bug35084() {
+        RuntimeException ex = assertThrows(RuntimeException.class, super::bug35084);
+        assertEquals("Not Implemented", ex.getMessage());
     }
 
     @Override
     @Test
-    public void getCellComment() throws IOException {
+    public void getCellComment() {
         // TODO: reading cell comments via Sheet does not work currently as it tries
         // to access the underlying sheet for this, but comments are stored as
         // properties on Cells...
@@ -119,9 +116,8 @@ public final class TestSXSSFSheet extends BaseTestXSheet {
             sheet.createRow(3);
             sheet.createRow(4);
 
-            thrown.expect(Throwable.class);
-            thrown.expectMessage("Attempting to write a row[1] in the range [0,1] that is already written to disk.");
-            sheet.createRow(1);
+            Throwable ex = assertThrows(Throwable.class, () -> sheet.createRow(1));
+            assertEquals("Attempting to write a row[1] in the range [0,1] that is already written to disk.", ex.getMessage());
         }
     }
 
index 91ee3a38a38f2036fe52bff85126d512e595c24f..5c60d2d69bdb10eabbb846b409fc473119f3e60b 100644 (file)
@@ -21,6 +21,7 @@ import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThrows;
 import static org.junit.Assert.assertTrue;
 
 import java.io.ByteArrayInputStream;
@@ -39,16 +40,11 @@ import org.apache.poi.hsmf.datatypes.MAPIProperty;
 import org.apache.poi.hsmf.datatypes.Types;
 import org.apache.poi.util.IOUtils;
 import org.apache.poi.util.LittleEndian;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 
 public final class TestHMEFMessage {
     private static final POIDataSamples _samples = POIDataSamples.getHMEFInstance();
 
-    @Rule
-    public ExpectedException thrown =  ExpectedException.none();
-
     @Test
     public void testCounts() throws Exception {
         HMEFMessage msg = openSample("quick-winmail.dat");
@@ -161,12 +157,13 @@ public final class TestHMEFMessage {
     }
 
     @Test
-    public void testInvalidMessage() throws Exception {
+    public void testInvalidMessage() {
         InputStream str = new ByteArrayInputStream(new byte[4]);
-
-        thrown.expect(IllegalArgumentException.class);
-        thrown.expectMessage("TNEF signature not detected in file, expected 574529400 but got 0");
-        new HMEFMessage(str);
+        IllegalArgumentException ex = assertThrows(
+            IllegalArgumentException.class,
+            () -> new HMEFMessage(str)
+        );
+        assertEquals("TNEF signature not detected in file, expected 574529400 but got 0", ex.getMessage());
     }
 
     @Test
@@ -200,10 +197,11 @@ public final class TestHMEFMessage {
         LittleEndian.putUShort(90, out);
 
         InputStream str = new ByteArrayInputStream(out.toByteArray());
-
-        thrown.expect(IllegalStateException.class);
-        thrown.expectMessage("Unhandled level 90");
-        new HMEFMessage(str);
+        IllegalStateException ex = assertThrows(
+            IllegalStateException.class,
+            () -> new HMEFMessage(str)
+        );
+        assertEquals("Unhandled level 90", ex.getMessage());
     }
 
     @Test
index 681cd467083090d101ac6db4a4543e1ce5cc68ad..bdb5bba4632c59f873c172fce8d8f680d946e84a 100644 (file)
@@ -17,6 +17,7 @@
 package org.apache.poi.hslf.dev;
 
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThrows;
 
 import java.io.File;
 import java.io.PrintStream;
@@ -36,9 +37,7 @@ import org.apache.poi.util.IOUtils;
 import org.apache.poi.util.NullPrintStream;
 import org.junit.After;
 import org.junit.Before;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 import org.junit.runner.RunWith;
 import org.junit.runners.Parameterized;
 
@@ -58,9 +57,6 @@ public abstract class BasePPTIteratingTest {
         ENCRYPTED_FILES.add("Password_Protected-hello.ppt");
     }
 
-    @Rule
-    public ExpectedException thrown = ExpectedException.none();
-
     protected static final Map<String,Class<? extends Throwable>> EXCLUDED =
             new HashMap<>();
 
@@ -112,24 +108,29 @@ public abstract class BasePPTIteratingTest {
     @Test
     public void testAllFiles() throws Exception {
         String fileName = file.getName();
+        Class<? extends Throwable> t = null;
         if (EXCLUDED.containsKey(fileName)) {
-            thrown.expect(EXCLUDED.get(fileName));
+            t = EXCLUDED.get(fileName);
+        } else if (getFailedOldFiles().contains(fileName)) {
+            t = OldPowerPointFormatException.class;
+        } else if (getFailedEncryptedFiles().contains(fileName)) {
+            t = EncryptedPowerPointFileException.class;
         }
 
-        try {
+        if (t == null) {
             runOneFile(file);
-        } catch (OldPowerPointFormatException e) {
-            // expected for some files
-            if(!OLD_FILES.contains(file.getName())) {
-                throw e;
-            }
-        } catch (EncryptedPowerPointFileException e) {
-            // expected for some files
-            if(!ENCRYPTED_FILES.contains(file.getName())) {
-                throw e;
-            }
+        } else {
+            assertThrows(t, () -> runOneFile(file));
         }
     }
 
     abstract void runOneFile(File pFile) throws Exception;
+
+    protected Set<String> getFailedEncryptedFiles() {
+        return ENCRYPTED_FILES;
+    }
+
+    protected Set<String> getFailedOldFiles() {
+        return OLD_FILES;
+    }
 }
index de2f7721c29edf2e0829fd6a88d0fd9a3c9aeddd..7ff2349fbd82388cdd0cbe57cbecd6dabe3ae2fa 100644 (file)
 ==================================================================== */
 package org.apache.poi.hslf.dev;
 
-import org.apache.poi.EmptyFileException;
-import org.apache.poi.hslf.HSLFTestDataSamples;
-import org.junit.Test;
+import static org.junit.Assert.assertThrows;
 
 import java.io.File;
+import java.util.Collections;
+import java.util.Set;
 
-import static org.junit.Assert.fail;
+import org.apache.poi.EmptyFileException;
+import org.apache.poi.hslf.HSLFTestDataSamples;
+import org.junit.Test;
 
 public class TestPPTXMLDump extends BasePPTIteratingTest {
     @Test
@@ -34,16 +36,21 @@ public class TestPPTXMLDump extends BasePPTIteratingTest {
                 HSLFTestDataSamples.getSampleFile("pictures.ppt").getAbsolutePath()
         });
 
-        try {
-            PPTXMLDump.main(new String[]{"invalidfile"});
-            fail("Should catch exception here");
-        } catch (EmptyFileException e) {
-            // expected here
-        }
+        assertThrows(EmptyFileException.class, () -> PPTXMLDump.main(new String[]{"invalidfile"}));
     }
 
     @Override
     void runOneFile(File pFile) throws Exception {
         PPTXMLDump.main(new String[]{pFile.getAbsolutePath()});
     }
+
+    @Override
+    protected Set<String> getFailedEncryptedFiles() {
+        return Collections.emptySet();
+    }
+
+    @Override
+    protected Set<String> getFailedOldFiles() {
+        return Collections.emptySet();
+    }
 }
index e749d7586d38d05a8e9489981b0f321fa2ca42e5..9a6445e1e2a23229b0dd55970c0ebc1bdf79a7f1 100644 (file)
 ==================================================================== */
 package org.apache.poi.hslf.dev;
 
-import org.apache.poi.EmptyFileException;
-import org.apache.poi.hslf.HSLFTestDataSamples;
-import org.apache.poi.util.IOUtils;
-import org.junit.Test;
+import static org.junit.Assert.fail;
 
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
+import java.util.Collections;
 import java.util.HashSet;
 import java.util.Set;
 
-import static org.junit.Assert.fail;
+import org.apache.poi.EmptyFileException;
+import org.apache.poi.hslf.HSLFTestDataSamples;
+import org.apache.poi.util.IOUtils;
+import org.junit.Test;
 
 public class TestSlideShowDumper extends BasePPTIteratingTest {
     private static final Set<String> FAILING = new HashSet<>();
@@ -39,8 +40,6 @@ public class TestSlideShowDumper extends BasePPTIteratingTest {
 
     @Test
     public void testMain() throws IOException {
-        SlideShowDumper.main(new String[0]);
-
         // SlideShowDumper calls IOUtils.toByteArray(is), which would fail if a different size is defined
         IOUtils.setByteArrayMaxOverride(-1);
 
@@ -76,4 +75,14 @@ public class TestSlideShowDumper extends BasePPTIteratingTest {
             }
         }
     }
+
+    @Override
+    protected Set<String> getFailedEncryptedFiles() {
+        return Collections.emptySet();
+    }
+
+    @Override
+    protected Set<String> getFailedOldFiles() {
+        return Collections.emptySet();
+    }
 }
\ No newline at end of file
index 8158b5c54791b809290a10f5cb6c42876a28ae8f..dbab32a041a764b8e7473c129a3ee09efb6d688a 100644 (file)
 ==================================================================== */
 package org.apache.poi.hslf.dev;
 
-import org.apache.poi.EmptyFileException;
-import org.apache.poi.hslf.HSLFTestDataSamples;
-import org.junit.Test;
+import static org.junit.Assert.fail;
 
 import java.io.File;
 import java.io.IOException;
 
-import static org.junit.Assert.fail;
+import org.apache.poi.EmptyFileException;
+import org.apache.poi.hslf.HSLFTestDataSamples;
+import org.junit.Test;
 
 public class TestSlideShowRecordDumper extends BasePPTIteratingTest {
     @Test
     public void testMain() throws IOException {
-        SlideShowRecordDumper.main(new String[0]);
-
         SlideShowRecordDumper.main(new String[] {
                 HSLFTestDataSamples.getSampleFile("slide_master.ppt").getAbsolutePath(),
         });
index bda78bcf6d5b631df8411c2b9c9053943127a4e7..7907012cfb42fafdded1d9d382b580f9537b59f7 100644 (file)
@@ -22,8 +22,8 @@ import static org.hamcrest.CoreMatchers.endsWith;
 import static org.hamcrest.CoreMatchers.hasItem;
 import static org.hamcrest.CoreMatchers.not;
 import static org.hamcrest.CoreMatchers.startsWith;
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 import static org.junit.Assume.assumeNoException;
index a609ef7a26b74f4c8e112cf55a8dd6fbc0b89bcd..688ea0088d839bc81fae029fe913e02342c5cfb6 100644 (file)
 
 package org.apache.poi.hpsf.basic;
 
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.core.IsEqual.equalTo;
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
index 262aafdb3b72e65f2807eb71bd7ef3f5fa6eb4ee..823dc4418ee37cd02cefece7f9d27aaaa9957ce9 100644 (file)
@@ -17,9 +17,9 @@
 package org.apache.poi.hssf.dev;
 
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThrows;
 
 import java.io.File;
-import java.io.FileInputStream;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -27,10 +27,7 @@ import java.util.Locale;
 import java.util.Map;
 
 import org.apache.poi.POIDataSamples;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 import org.junit.runner.RunWith;
 import org.junit.runners.Parameterized;
 import org.junit.runners.Parameterized.Parameter;
@@ -44,11 +41,7 @@ import org.junit.runners.Parameterized.Parameters;
  */
 @RunWith(Parameterized.class)
 public abstract class BaseTestIteratingXLS {
-    @Rule
-    public ExpectedException thrown = ExpectedException.none();
-
-       protected static final Map<String,Class<? extends Throwable>> EXCLUDED =
-            new HashMap<>();
+       protected static final Map<String,Class<? extends Throwable>> EXCLUDED = new HashMap<>();
 
     @Parameters(name="{index}: {0}")
     public static Iterable<Object[]> files() {
@@ -80,20 +73,15 @@ public abstract class BaseTestIteratingXLS {
        @Test
        public void testMain() throws Exception {
            String fileName = file.getName();
-           if (EXCLUDED.containsKey(fileName)) {
-               thrown.expect(EXCLUDED.get(fileName));
-           }
-
-               try {
-                       runOneFile(file);
-               } catch (Exception e) {
-                       // try to read it in HSSFWorkbook to quickly fail if we cannot read the file there at all and thus probably should use EXCLUDED instead
-            try (FileInputStream stream = new FileInputStream(file); HSSFWorkbook wb = new HSSFWorkbook(stream)) {
-                assertNotNull(wb);
-            }
 
-                       throw e;
-               }
+           Class<? extends Throwable> t = EXCLUDED.get(fileName);
+
+        if (t == null) {
+            runOneFile(file);
+        } else {
+            assertThrows(t, () -> runOneFile(file));
+        }
+
        }
 
        abstract void runOneFile(File pFile) throws Exception;
index 75adb444a420e1a4de57ccb1dfa77f8e71484f2c..f5cce1b268662ed2183a04fc07faf68257cd8e2e 100644 (file)
@@ -22,26 +22,21 @@ import java.io.InputStream;
 import java.io.OutputStreamWriter;
 import java.io.PrintWriter;
 
-import org.apache.poi.EncryptedDocumentException;
-import org.apache.poi.POIDataSamples;
 import org.apache.poi.hssf.OldExcelFormatException;
-import org.apache.poi.hssf.record.RecordInputStream;
 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 import org.apache.poi.util.LocaleUtil;
 import org.apache.poi.util.NullOutputStream;
 import org.apache.poi.util.RecordFormatException;
 import org.junit.BeforeClass;
-import org.junit.Ignore;
-import org.junit.Test;
 
 public class TestBiffViewer extends BaseTestIteratingXLS {
     @BeforeClass
     public static void setup() {
         EXCLUDED.clear();
-        EXCLUDED.put("35897-type4.xls", EncryptedDocumentException.class); // unsupported crypto api header
-        EXCLUDED.put("51832.xls", EncryptedDocumentException.class);
-        EXCLUDED.put("xor-encryption-abc.xls", EncryptedDocumentException.class);
-        EXCLUDED.put("password.xls", EncryptedDocumentException.class);
+        EXCLUDED.put("35897-type4.xls", IllegalArgumentException.class); // unsupported crypto api header
+        EXCLUDED.put("51832.xls", IllegalArgumentException.class);
+        EXCLUDED.put("xor-encryption-abc.xls", RecordFormatException.class);
+        EXCLUDED.put("password.xls", IllegalArgumentException.class);
         EXCLUDED.put("46904.xls", OldExcelFormatException.class);
         EXCLUDED.put("59074.xls", OldExcelFormatException.class);
         EXCLUDED.put("testEXCEL_2.xls", OldExcelFormatException.class);  // Biff 2 / Excel 2, pre-OLE2
@@ -50,11 +45,11 @@ public class TestBiffViewer extends BaseTestIteratingXLS {
         EXCLUDED.put("testEXCEL_5.xls", OldExcelFormatException.class);  // Biff 5 / Excel 5
         EXCLUDED.put("60284.xls", OldExcelFormatException.class); // Biff 5 / Excel 5
         EXCLUDED.put("testEXCEL_95.xls", OldExcelFormatException.class); // Biff 5 / Excel 95
-        EXCLUDED.put("43493.xls", RecordInputStream.LeftoverDataException.class);  // HSSFWorkbook cannot open it as well
+        EXCLUDED.put("43493.xls", RecordFormatException.class);  // HSSFWorkbook cannot open it as well
         // EXCLUDED.put("44958_1.xls", RecordInputStream.LeftoverDataException.class);
         EXCLUDED.put("50833.xls", IllegalArgumentException.class);       // "Name is too long" when setting username
         EXCLUDED.put("XRefCalc.xls", RuntimeException.class);            // "Buffer overrun"
-        EXCLUDED.put("61300.xls", RecordFormatException.class);
+        EXCLUDED.put("61300.xls", IndexOutOfBoundsException.class);
         EXCLUDED.put("64130.xls", OldExcelFormatException.class); //Biff 5
     }
 
@@ -68,11 +63,11 @@ public class TestBiffViewer extends BaseTestIteratingXLS {
         }
     }
 
-    @Test
-    @Ignore("only used for manual tests")
-    @SuppressWarnings("java:S2699")
-    public void testOneFile() throws Exception {
-        POIDataSamples samples = POIDataSamples.getSpreadSheetInstance();
-        runOneFile(samples.getFile("43493.xls"));
-    }
+//    @Test
+//    @Ignore("only used for manual tests")
+//    @SuppressWarnings("java:S2699")
+//    public void testOneFile() throws Exception {
+//        POIDataSamples samples = POIDataSamples.getSpreadSheetInstance();
+//        runOneFile(samples.getFile("43493.xls"));
+//    }
 }
index d92239bbfe136cf6971df1da11e0c1e294499fce..c0ef0fd7dccb4fb35f73c76f80ebe3c36b4376ad 100644 (file)
 package org.apache.poi.hssf.model;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThrows;
 
 import org.apache.poi.hssf.record.ColumnInfoRecord;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 
 public final class TestSheetAdditional {
-       @Rule
-       public ExpectedException thrown= ExpectedException.none();
-
        @Test
        public void testGetCellWidth() {
                InternalSheet sheet = InternalSheet.createSheet();
@@ -65,8 +61,10 @@ public final class TestSheetAdditional {
                sheet.setColumnWidth(0, 255*256);
 
                // over the limit
-               thrown.expect(IllegalArgumentException.class);
-               thrown.expectMessage("The maximum column width for an individual cell is 255 characters.");
-               sheet.setColumnWidth(0, 256*256);
+               IllegalArgumentException ex = assertThrows(
+                       IllegalArgumentException.class,
+                       () -> sheet.setColumnWidth(0, 256*256)
+               );
+               assertEquals("The maximum column width for an individual cell is 255 characters.", ex.getMessage());
        }
 }
index a716717ad9937d69b8aec4f1a3f19bd79755c932..757da3c9ca23aaee9a2f3fbf7820c818c6f26cb6 100644 (file)
@@ -19,16 +19,15 @@ package org.apache.poi.hssf.record;
 
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
 
 import java.io.ByteArrayInputStream;
 
 import org.apache.poi.EncryptedDocumentException;
 import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
 import org.apache.poi.util.HexRead;
-import org.junit.After;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 
 /**
  * Tests for {@link RecordFactoryInputStream}
@@ -57,10 +56,7 @@ public final class TestRecordFactoryInputStream {
        private static final String SAMPLE_WINDOW1 = "3D 00 12 00"
                + "00 00 00 00 40 38 55 23 38 00 00 00 00 00 01 00 58 02";
 
-       @Rule
-       public ExpectedException expectedEx = ExpectedException.none();
 
-       
        /**
         * Makes sure that a default password mismatch condition is represented with {@link EncryptedDocumentException}
         */
@@ -76,11 +72,13 @@ public final class TestRecordFactoryInputStream {
                                + SAMPLE_WINDOW1_ENCR1
                );
 
-           expectedEx.expect(EncryptedDocumentException.class);
-           expectedEx.expectMessage("Default password is invalid for salt/verifier/verifierHash");
-               createRFIS(dataWrongDefault);
+               EncryptedDocumentException ex = assertThrows(
+                       EncryptedDocumentException.class,
+                       () -> createRFIS(dataWrongDefault)
+               );
+               assertTrue(ex.getMessage().contains("Default password is invalid for salt/verifier/verifierHash"));
        }
-       
+
     @Test
     public void defaultPasswordOK() {
         // This encodng depends on docId, password and stream position
@@ -96,7 +94,7 @@ public final class TestRecordFactoryInputStream {
         RecordFactoryInputStream rfis = createRFIS(dataCorrectDefault);
         confirmReadInitialRecords(rfis);
     }
-       
+
 
        /**
         * Makes sure that an incorrect user supplied password condition is represented with {@link EncryptedDocumentException}
@@ -113,12 +111,13 @@ public final class TestRecordFactoryInputStream {
                                + SAMPLE_WINDOW1_ENCR2
                );
 
-               expectedEx.expect(EncryptedDocumentException.class);
-               expectedEx.expectMessage("Supplied password is invalid for salt/verifier/verifierHash");
-
                Biff8EncryptionKey.setCurrentUserPassword("passw0rd");
                try {
-                       createRFIS(dataWrongDefault);
+                       EncryptedDocumentException ex = assertThrows(
+                               EncryptedDocumentException.class,
+                               () -> createRFIS(dataWrongDefault)
+                       );
+                       assertEquals("Supplied password is invalid for salt/verifier/verifierHash", ex.getMessage());
                } finally {
                        Biff8EncryptionKey.setCurrentUserPassword(null);
                }
@@ -144,8 +143,8 @@ public final class TestRecordFactoryInputStream {
                        Biff8EncryptionKey.setCurrentUserPassword(null);
                }
     }
-       
-       
+
+
        /**
         * makes sure the record stream starts with {@link BOFRecord}, {@link FilePassRecord} and then {@link WindowOneRecord}
         * The third record is decrypted so this method also checks its content.
index 1862efeb6a23d26bd208cb9ca950027afbbd1800..2f4217400bcc90ffbd58497f17141c0a01a93c87 100644 (file)
@@ -21,6 +21,7 @@ import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertThrows;
 import static org.junit.Assert.assertTrue;
 
 import java.util.ArrayList;
@@ -54,20 +55,14 @@ import org.apache.poi.hssf.usermodel.HSSFSheet;
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 import org.apache.poi.util.HexRead;
 import org.apache.poi.util.RecordFormatException;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 
 /**
  * Tess for {@link PageSettingsBlock}
  */
 public final class TestPageSettingsBlock {
-       @Rule
-       public ExpectedException thrown = ExpectedException.none();
-
        @Test
        public void testPrintSetup_bug46548() {
-
                // PageSettingBlock in this file contains PLS (sid=x004D) record
                // followed by ContinueRecord (sid=x003C)
                HSSFWorkbook wb = HSSFTestDataSamples.openSampleWorkbook("ex46548-23133.xls");
@@ -202,14 +197,16 @@ public final class TestPageSettingsBlock {
        public void testDuplicatePSBRecord_bug47199() {
                // Hypothetical setup of PSB records which should cause POI to crash
                org.apache.poi.hssf.record.Record[] recs = {
-                               new HeaderRecord("&LSales Figures"),
-                               new HeaderRecord("&LInventory"),
+                       new HeaderRecord("&LSales Figures"),
+                       new HeaderRecord("&LInventory"),
                };
                RecordStream rs = new RecordStream(Arrays.asList(recs), 0);
 
-               thrown.expectMessage("Duplicate PageSettingsBlock record (sid=0x14)");
-               thrown.expect(RecordFormatException.class);
-               new PageSettingsBlock(rs);
+               RecordFormatException ex = assertThrows(
+                       RecordFormatException.class,
+                       () -> new PageSettingsBlock(rs)
+               );
+               assertEquals("Duplicate PageSettingsBlock record (sid=0x14)", ex.getMessage());
        }
 
        /**
index 7d7650de25dcb6e81698ecff49ec55c09f05f8c7..446d9b1d0e882ca2f1b17d16361db6b61751e6b6 100644 (file)
@@ -92,9 +92,7 @@ import org.junit.AfterClass;
 import org.junit.Assume;
 import org.junit.BeforeClass;
 import org.junit.Ignore;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 
 /**
  * Testcases for bugs entered in bugzilla
@@ -105,9 +103,6 @@ import org.junit.rules.ExpectedException;
  */
 public final class TestBugs extends BaseTestBugzillaIssues {
 
-    @Rule
-    public ExpectedException thrown = ExpectedException.none();
-
     public TestBugs() {
         super(HSSFITestDataProvider.instance);
     }
@@ -923,7 +918,7 @@ public final class TestBugs extends BaseTestBugzillaIssues {
     @Test
     public void bug45338() throws IOException {
         try (HSSFWorkbook wb = new HSSFWorkbook()) {
-            assertEquals(4, wb.getNumberOfFontsAsInt());
+            assertEquals(4, wb.getNumberOfFonts());
 
             HSSFSheet s = wb.createSheet();
             s.createRow(0);
@@ -931,7 +926,7 @@ public final class TestBugs extends BaseTestBugzillaIssues {
             s.getRow(0).createCell(0);
             s.getRow(1).createCell(0);
 
-            assertEquals(4, wb.getNumberOfFontsAsInt());
+            assertEquals(4, wb.getNumberOfFonts());
 
             HSSFFont f1 = wb.getFontAt(0);
             assertFalse(f1.getBold());
@@ -947,7 +942,7 @@ public final class TestBugs extends BaseTestBugzillaIssues {
             assertNull(wb.findFont(false, (short) 123, (short) 22, "Thingy", false, true, (short) 2, (byte) 2));
 
             HSSFFont nf = wb.createFont();
-            assertEquals(5, wb.getNumberOfFontsAsInt());
+            assertEquals(5, wb.getNumberOfFonts());
 
             assertEquals(5, nf.getIndex());
             assertEquals(nf, wb.getFontAt(5));
@@ -961,7 +956,7 @@ public final class TestBugs extends BaseTestBugzillaIssues {
             nf.setTypeOffset((short) 2);
             nf.setUnderline((byte) 2);
 
-            assertEquals(5, wb.getNumberOfFontsAsInt());
+            assertEquals(5, wb.getNumberOfFonts());
             assertEquals(nf, wb.getFontAt(5));
 
             // Find it now
@@ -1480,10 +1475,12 @@ public final class TestBugs extends BaseTestBugzillaIssues {
      * (is an excel 95 file though)
      */
     @Test
-    public void bug46904a() throws Exception {
-        thrown.expect(OldExcelFormatException.class);
-        thrown.expectMessage("The supplied spreadsheet seems to be Excel");
-        simpleTest("46904.xls");
+    public void bug46904a() {
+        OldExcelFormatException ex = assertThrows(
+            OldExcelFormatException.class,
+            () -> simpleTest("46904.xls")
+        );
+        assertTrue(ex.getMessage().contains("The supplied spreadsheet seems to be Excel"));
     }
 
     /**
@@ -2735,8 +2732,8 @@ public final class TestBugs extends BaseTestBugzillaIssues {
 
             assertEquals(CellType.BLANK, cell.getCellType());
             assertEquals("", cell.getStringCellValue());
-            thrown.expect(IllegalStateException.class);
-            assertNull(cell.getCellFormula());
+
+            assertThrows(IllegalStateException.class, cell::getCellFormula);
         }
     }
 
@@ -2835,9 +2832,11 @@ public final class TestBugs extends BaseTestBugzillaIssues {
             DocumentEntry entry =
                     (DocumentEntry) poifs.getRoot().getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
 
-            thrown.expect(RuntimeException.class);
-            thrown.expectMessage("Can't read negative number of bytes");
-            new PropertySet(new DocumentInputStream(entry));
+            RuntimeException ex = assertThrows(
+                RuntimeException.class,
+                () -> new PropertySet(new DocumentInputStream(entry))
+            );
+            assertEquals("Can't read negative number of bytes", ex.getMessage());
         }
     }
 
index 821a14b9ef2f5e3c37a301253c76b1e66aa18419..09906b8e2750ec7f917bebb1db52585f70225149 100644 (file)
 package org.apache.poi.hssf.usermodel;
 
 import static org.apache.poi.hssf.HSSFTestDataSamples.writeOutAndReadBack;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-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.Assert.*;
 
 import java.io.IOException;
 import java.util.ArrayList;
@@ -1042,9 +1034,11 @@ public final class TestHSSFSheet extends BaseTestSheet {
             Sheet sheet = wb.createSheet();
             sheet.showInPane(2, 3);
 
-            thrown.expect(IllegalArgumentException.class);
-            thrown.expectMessage("Maximum row number is 65535");
-            sheet.showInPane(Integer.MAX_VALUE, 3);
+            IllegalArgumentException ex = assertThrows(
+                IllegalArgumentException.class,
+                () -> sheet.showInPane(Integer.MAX_VALUE, 3)
+            );
+            assertEquals("Maximum row number is 65535", ex.getMessage());
         }
     }
 
index 583ef24f50689e35d615b49ffde90ca8bab32f51..91894113bda99b955f1f881cccea3cded783f55a 100644 (file)
@@ -17,9 +17,9 @@
 
 package org.apache.poi.poifs.crypt;
 
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.core.IsEqual.equalTo;
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
@@ -37,9 +37,9 @@ import org.junit.Ignore;
 import org.junit.Test;
 
 public class TestXorEncryption {
-    
+
     private static final HSSFTestDataSamples samples = new HSSFTestDataSamples();
-    
+
     @Test
     public void testXorEncryption() {
         // Xor-Password: abc
index 4e235b66c771714751a88ce7326afc8d196192c1..1b154bd89dffdf512bcc57191e045c73738573a4 100644 (file)
@@ -20,6 +20,8 @@ package org.apache.poi.poifs.filesystem;
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
 
 import java.io.ByteArrayInputStream;
 import java.io.File;
@@ -27,9 +29,7 @@ import java.io.IOException;
 import java.io.InputStream;
 
 import org.apache.poi.hssf.HSSFTestDataSamples;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 
 /**
  * Class to test that POIFS complains when given an Office 2003 XML
@@ -37,32 +37,23 @@ import org.junit.rules.ExpectedException;
  */
 public class TestOfficeXMLException {
 
-    @Rule
-    public ExpectedException thrown = ExpectedException.none();
-
-
     private static InputStream openSampleStream(String sampleFileName) {
         return HSSFTestDataSamples.openSampleFileStream(sampleFileName);
     }
 
     @Test
     public void testOOXMLException() throws IOException {
-        thrown.expect(OfficeXmlFileException.class);
-        thrown.expectMessage("You are calling the part of POI that deals with OLE2 Office Documents");
-
-        try (InputStream in = openSampleStream("sample.xlsx");
-             POIFSFileSystem fs = new POIFSFileSystem(in)) {
-
+        try (InputStream in = openSampleStream("sample.xlsx")) {
+            OfficeXmlFileException ex = assertThrows(OfficeXmlFileException.class, () -> new POIFSFileSystem(in));
+            assertTrue(ex.getMessage().contains("You are calling the part of POI that deals with OLE2 Office Documents"));
         }
     }
 
     @Test
     public void test2003XMLException() throws IOException {
-        thrown.expect(NotOLE2FileException.class);
-        thrown.expectMessage("The supplied data appears to be a raw XML file");
-
-        try (InputStream in = openSampleStream("SampleSS.xml");
-             POIFSFileSystem fs = new POIFSFileSystem(in)) {
+        try (InputStream in = openSampleStream("SampleSS.xml")) {
+            NotOLE2FileException ex = assertThrows(NotOLE2FileException.class, () -> new POIFSFileSystem(in));
+            assertTrue(ex.getMessage().contains("The supplied data appears to be a raw XML file"));
         }
     }
 
index 4de08c4c5caf8d88f109e00bbecaa2f0fc1e407f..2a235d3940f16ecb62b2a8150dadac9d90d2cbe1 100644 (file)
 
 package org.apache.poi.poifs.filesystem;
 
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.core.IsEqual.equalTo;
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
 
 import java.io.ByteArrayOutputStream;
 import java.io.File;
@@ -32,16 +34,11 @@ import java.util.List;
 import org.apache.poi.POIDataSamples;
 import org.apache.poi.util.IOUtils;
 import org.apache.poi.util.RecordFormatException;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 
 public class TestOle10Native {
     private static final POIDataSamples dataSamples = POIDataSamples.getPOIFSInstance();
 
-    @Rule
-    public ExpectedException thrown = ExpectedException.none();
-
     @Test
     public void testOleNative() throws IOException, Ole10NativeException {
         POIFSFileSystem fs = new POIFSFileSystem(dataSamples.openResourceAsStream("oleObject1.bin"));
@@ -101,11 +98,14 @@ public class TestOle10Native {
     }
 
     @Test
-    public void testOleNativeOOM() throws IOException, Ole10NativeException {
-        POIFSFileSystem fs = new POIFSFileSystem(dataSamples.openResourceAsStream("60256.bin"));
-        thrown.expect(RecordFormatException.class);
-        thrown.expectMessage("Tried to allocate");
-        Ole10Native.createFromEmbeddedOleObject(fs);
+    public void testOleNativeOOM() throws IOException {
+        try (POIFSFileSystem fs = new POIFSFileSystem(dataSamples.openResourceAsStream("60256.bin"))) {
+            RecordFormatException ex = assertThrows(
+                RecordFormatException.class,
+                () -> Ole10Native.createFromEmbeddedOleObject(fs)
+            );
+            assertTrue(ex.getMessage().contains("Tried to allocate"));
+        }
     }
 
 }
index 5153cb37e1cc07f1cac42092d5a3b7926bf1801e..9860935c12561e94f6c282302cb99d801b5e7644 100644 (file)
@@ -19,12 +19,12 @@ package org.apache.poi.poifs.filesystem;
 
 import static java.nio.charset.StandardCharsets.UTF_8;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThrows;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
-import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.UnsupportedEncodingException;
@@ -42,9 +42,7 @@ import org.apache.poi.poifs.common.POIFSConstants;
 import org.apache.poi.poifs.storage.BATBlock;
 import org.apache.poi.poifs.storage.HeaderBlock;
 import org.apache.poi.util.IOUtils;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 
 /**
  * Tests for the older OPOIFS-based POIFSFileSystem
@@ -166,9 +164,6 @@ public final class TestPOIFSFileSystem {
                }
        }
 
-       @Rule
-       public ExpectedException expectedEx = ExpectedException.none();
-
        /**
         * Check that we do the right thing when the list of which
         *  sectors are BAT blocks points off the list of
@@ -176,12 +171,13 @@ public final class TestPOIFSFileSystem {
         */
        @Test
        public void testFATandDIFATsectors() throws Exception {
-        // Open the file up
-               expectedEx.expect(IndexOutOfBoundsException.class);
-               expectedEx.expectMessage("Block 1148 not found");
                try (InputStream stream = _samples.openResourceAsStream("ReferencesInvalidSectors.mpp")) {
-                       new POIFSFileSystem(stream);
-                       fail("File is corrupt and shouldn't have been opened");
+                       IndexOutOfBoundsException ex = assertThrows(
+                               "File is corrupt and shouldn't have been opened",
+                               IndexOutOfBoundsException.class,
+                               () -> new POIFSFileSystem(stream)
+                       );
+                       assertTrue(ex.getMessage().contains("Block 1148 not found"));
                }
        }
 
index c6a0a6a77bdfad5ee1034beb6fb852ff86412bc6..af313172a7a3c0909355aa5f3376e2ce8af0020f 100644 (file)
 
 package org.apache.poi.poifs.filesystem;
 
-import static org.hamcrest.core.IsCollectionContaining.hasItem;
+import static org.hamcrest.CoreMatchers.hasItem;
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.core.IsEqual.equalTo;
 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.assertThat;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
index 9f7a21a0dffaf072502459fa3b1b0e0a14c3f6a2..7faedd8c03302d0478f3248ec9a520fcb8e132dd 100644 (file)
@@ -20,6 +20,8 @@
 package org.apache.poi.ss.formula;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
 
 import java.io.IOException;
 
@@ -37,9 +39,7 @@ import org.apache.poi.ss.usermodel.CellValue;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.FixMethodOrder;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 import org.junit.runners.MethodSorters;
 
 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
@@ -67,14 +67,10 @@ public class TestFunctionRegistry {
         fe = null;
     }
 
-    @Rule
-    public ExpectedException thrown = ExpectedException.none();
-
-    @Test
+    @Test(expected = NotImplementedException.class)
        public void testRegisterInRuntimeA() {
         HSSFCell cellA = row.createCell(0);
         cellA.setCellFormula("FISHER(A5)");
-        thrown.expect(NotImplementedException.class);
         fe.evaluate(cellA);
     }
 
@@ -87,11 +83,10 @@ public class TestFunctionRegistry {
         assertEquals(ErrorEval.NA.getErrorCode(), cv.getErrorValue());
     }
 
-    @Test
+    @Test(expected = NotImplementedException.class)
     public void testRegisterInRuntimeC() {
         HSSFCell cellB = row.createCell(1);
         cellB.setCellFormula("CUBEMEMBERPROPERTY(A5)");
-        thrown.expect(NotImplementedException.class);
         fe.evaluate(cellB);
     }
 
@@ -112,24 +107,31 @@ public class TestFunctionRegistry {
 
     @Test
     public void testExceptionsA() {
-        thrown.expect(IllegalArgumentException.class);
-        thrown.expectMessage("POI already implememts SUM. You cannot override POI's implementations of Excel functions");
-        FunctionEval.registerFunction("SUM", TestFunctionRegistry::na);
+        IllegalArgumentException ex = assertThrows(
+            IllegalArgumentException.class,
+            () -> FunctionEval.registerFunction("SUM", TestFunctionRegistry::na)
+        );
+        assertEquals("POI already implements SUM. You cannot override POI's implementations of Excel functions", ex.getMessage());
     }
 
     @Test
     public void testExceptionsB() {
-        thrown.expect(IllegalArgumentException.class);
-        thrown.expectMessage("Unknown function: SUMXXX");
-        FunctionEval.registerFunction("SUMXXX", TestFunctionRegistry::na);
+        IllegalArgumentException ex = assertThrows(
+            IllegalArgumentException.class,
+            () -> FunctionEval.registerFunction("SUMXXX", TestFunctionRegistry::na)
+        );
+        assertTrue(ex.getMessage().contains("Unknown function: SUMXXX"));
     }
 
     @Test
     public void testExceptionsC() {
-        thrown.expect(IllegalArgumentException.class);
-        thrown.expectMessage("ISODD is a function from the Excel Analysis Toolpack. " +
-            "Use AnalysisToolpack.registerFunction(String name, FreeRefFunction func) instead.");
-        FunctionEval.registerFunction("ISODD", TestFunctionRegistry::na);
+        IllegalArgumentException ex = assertThrows(
+            IllegalArgumentException.class,
+            () -> FunctionEval.registerFunction("ISODD", TestFunctionRegistry::na)
+        );
+        assertEquals("ISODD is a function from the Excel Analysis Toolpack. " +
+             "Use AnalysisToolpack.registerFunction(String name, FreeRefFunction func) instead.",
+             ex.getMessage());
     }
 
     private static ValueEval atpFunc(ValueEval[] args, OperationEvaluationContext ec) {
@@ -138,23 +140,30 @@ public class TestFunctionRegistry {
 
     @Test
     public void testExceptionsD() {
-        thrown.expect(IllegalArgumentException.class);
-        thrown.expectMessage("POI already implememts ISODD. You cannot override POI's implementations of Excel functions");
-        AnalysisToolPak.registerFunction("ISODD", TestFunctionRegistry::atpFunc);
+        IllegalArgumentException ex = assertThrows(
+            IllegalArgumentException.class,
+            () -> AnalysisToolPak.registerFunction("ISODD", TestFunctionRegistry::atpFunc)
+        );
+        assertEquals("POI already implements ISODD. You cannot override POI's implementations of Excel functions", ex.getMessage());
     }
 
     @Test
     public void testExceptionsE() {
-        thrown.expect(IllegalArgumentException.class);
-        thrown.expectMessage("ISODDXXX is not a function from the Excel Analysis Toolpack.");
-        AnalysisToolPak.registerFunction("ISODDXXX", TestFunctionRegistry::atpFunc);
+        IllegalArgumentException ex = assertThrows(
+            IllegalArgumentException.class,
+            () -> AnalysisToolPak.registerFunction("ISODDXXX", TestFunctionRegistry::atpFunc)
+        );
+        assertEquals("ISODDXXX is not a function from the Excel Analysis Toolpack.", ex.getMessage());
     }
 
     @Test
     public void testExceptionsF() {
-        thrown.expect(IllegalArgumentException.class);
-        thrown.expectMessage("SUM is a built-in Excel function. " +
-             "Use FunctoinEval.registerFunction(String name, Function func) instead.");
-        AnalysisToolPak.registerFunction("SUM", TestFunctionRegistry::atpFunc);
+        IllegalArgumentException ex = assertThrows(
+            IllegalArgumentException.class,
+            () -> AnalysisToolPak.registerFunction("SUM", TestFunctionRegistry::atpFunc)
+        );
+        assertEquals("SUM is a built-in Excel function. " +
+             "Use FunctoinEval.registerFunction(String name, Function func) instead.",
+             ex.getMessage());
     }
 }
index 578452fe5091bfab757a300bca4f10301aebde8b..70745ef9795a41aef353487aa4cdc20e8675d649 100644 (file)
@@ -19,6 +19,7 @@ package org.apache.poi.ss.formula.eval.forked;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThrows;
 
 import java.io.IOException;
 
@@ -28,15 +29,10 @@ import org.apache.poi.ss.formula.eval.NumberEval;
 import org.apache.poi.ss.usermodel.Row;
 import org.apache.poi.ss.usermodel.Sheet;
 import org.apache.poi.ss.usermodel.Workbook;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 
 public class BaseTestForkedEvaluator {
 
-    @Rule
-    public ExpectedException expectedEx = ExpectedException.none();
-
     protected Workbook newWorkbook() {
         return new HSSFWorkbook();
     }
@@ -66,34 +62,33 @@ public class BaseTestForkedEvaluator {
         */
        @Test
        public void testBasic() throws IOException {
-               Workbook wb = createWorkbook();
-
-               // The stability classifier is useful to reduce memory consumption of caching logic
-               IStabilityClassifier stabilityClassifier = (sheetIndex, rowIndex, columnIndex) -> sheetIndex == 1;
+               try (Workbook wb = createWorkbook()) {
 
-               ForkedEvaluator fe1 = ForkedEvaluator.create(wb, stabilityClassifier, null);
-               ForkedEvaluator fe2 = ForkedEvaluator.create(wb, stabilityClassifier, null);
+                       // The stability classifier is useful to reduce memory consumption of caching logic
+                       IStabilityClassifier stabilityClassifier = (sheetIndex, rowIndex, columnIndex) -> sheetIndex == 1;
 
-               // fe1 and fe2 can be used concurrently on separate threads
+                       ForkedEvaluator fe1 = ForkedEvaluator.create(wb, stabilityClassifier, null);
+                       ForkedEvaluator fe2 = ForkedEvaluator.create(wb, stabilityClassifier, null);
 
-               fe1.updateCell("Inputs", 0, 0, new NumberEval(4.0));
-               fe1.updateCell("Inputs", 0, 1, new NumberEval(1.1));
+                       // fe1 and fe2 can be used concurrently on separate threads
 
-               fe2.updateCell("Inputs", 0, 0, new NumberEval(1.2));
-               fe2.updateCell("Inputs", 0, 1, new NumberEval(2.0));
+                       fe1.updateCell("Inputs", 0, 0, new NumberEval(4.0));
+                       fe1.updateCell("Inputs", 0, 1, new NumberEval(1.1));
 
-               NumberEval eval1 = (NumberEval) fe1.evaluate("Calculations", 0, 0);
-               assertNotNull(eval1);
-               assertEquals(18.9, eval1.getNumberValue(), 0.0);
-               NumberEval eval2 = (NumberEval) fe2.evaluate("Calculations", 0, 0);
-               assertNotNull(eval2);
-               assertEquals(4.0, eval2.getNumberValue(), 0.0);
-               fe1.updateCell("Inputs", 0, 0, new NumberEval(3.0));
-               eval1 = (NumberEval) fe1.evaluate("Calculations", 0, 0);
-               assertNotNull(eval1);
-               assertEquals(13.9, eval1.getNumberValue(), 0.0);
+                       fe2.updateCell("Inputs", 0, 0, new NumberEval(1.2));
+                       fe2.updateCell("Inputs", 0, 1, new NumberEval(2.0));
 
-               wb.close();
+                       NumberEval eval1 = (NumberEval) fe1.evaluate("Calculations", 0, 0);
+                       assertNotNull(eval1);
+                       assertEquals(18.9, eval1.getNumberValue(), 0.0);
+                       NumberEval eval2 = (NumberEval) fe2.evaluate("Calculations", 0, 0);
+                       assertNotNull(eval2);
+                       assertEquals(4.0, eval2.getNumberValue(), 0.0);
+                       fe1.updateCell("Inputs", 0, 0, new NumberEval(3.0));
+                       eval1 = (NumberEval) fe1.evaluate("Calculations", 0, 0);
+                       assertNotNull(eval1);
+                       assertEquals(13.9, eval1.getNumberValue(), 0.0);
+               }
        }
 
        /**
@@ -108,13 +103,15 @@ public class BaseTestForkedEvaluator {
         */
        @Test
        public void testMissingInputCellH() throws IOException {
-           expectedEx.expect(UnsupportedOperationException.class);
-           expectedEx.expectMessage("Underlying cell 'A2' is missing in master sheet.");
 
                try (Workbook wb = createWorkbook()) {
                        ForkedEvaluator fe = ForkedEvaluator.create(wb, null, null);
                        // attempt update input at cell A2 (which is missing)
-                       fe.updateCell("Inputs", 1, 0, new NumberEval(4.0));
+                       UnsupportedOperationException ex = assertThrows(
+                               UnsupportedOperationException.class,
+                                () -> fe.updateCell("Inputs", 1, 0, new NumberEval(4.0))
+                       );
+                       assertEquals("Underlying cell 'A2' is missing in master sheet.", ex.getMessage());
                }
        }
 }
index 1264a15ca9e204dddf69334d320feda8e79bba2b..4579cefadde73c3183e3522c8f174ad6fb82afb9 100644 (file)
@@ -1014,21 +1014,21 @@ public abstract class BaseTestBugzillaIssues {
         try (Workbook wb = _testDataProvider.createWorkbook()) {
             int startingFonts = wb instanceof HSSFWorkbook ? 4 : 1;
 
-            assertEquals(startingFonts, wb.getNumberOfFontsAsInt());
+            assertEquals(startingFonts, wb.getNumberOfFonts());
 
             // Get a font, and slightly change it
             Font a = wb.createFont();
-            assertEquals(startingFonts + 1, wb.getNumberOfFontsAsInt());
+            assertEquals(startingFonts + 1, wb.getNumberOfFonts());
             a.setFontHeightInPoints((short) 23);
-            assertEquals(startingFonts + 1, wb.getNumberOfFontsAsInt());
+            assertEquals(startingFonts + 1, wb.getNumberOfFonts());
 
             // Get two more, unchanged
             /*Font b =*/
             wb.createFont();
-            assertEquals(startingFonts + 2, wb.getNumberOfFontsAsInt());
+            assertEquals(startingFonts + 2, wb.getNumberOfFonts());
             /*Font c =*/
             wb.createFont();
-            assertEquals(startingFonts + 3, wb.getNumberOfFontsAsInt());
+            assertEquals(startingFonts + 3, wb.getNumberOfFonts());
         }
     }
 
index 89594af0f92b8b28448a9df94c702b7f81eadb8b..30d80a73c71511141a8d77ca903c1b70120dbec2 100644 (file)
 
 package org.apache.poi.ss.usermodel;
 
-import static org.junit.Assert.*;
+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 java.io.IOException;
 
@@ -58,7 +64,7 @@ public abstract class BaseTestFont {
     @Test
     public final void testGetNumberOfFonts() throws IOException {
         Workbook wb = _testDataProvider.createWorkbook();
-        int num0 = wb.getNumberOfFontsAsInt();
+        int num0 = wb.getNumberOfFonts();
 
         Font f1=wb.createFont();
         f1.setBold(true);
@@ -103,7 +109,7 @@ public abstract class BaseTestFont {
         font.setFontName("Courier");
         int font1Idx = font.getIndexAsInt();
         wb1.createCellStyle().setFont(font);
-        assertEquals(num0 + 1, wb1.getNumberOfFontsAsInt());
+        assertEquals(num0 + 1, wb1.getNumberOfFonts());
 
         CellStyle cellStyleTitle=wb1.createCellStyle();
         cellStyleTitle.setFont(font);
@@ -114,7 +120,7 @@ public abstract class BaseTestFont {
         wb1.close();
         s1 = wb2.getSheetAt(0);
 
-        assertEquals(num0 + 1, wb2.getNumberOfFontsAsInt());
+        assertEquals(num0 + 1, wb2.getNumberOfFonts());
         int idx = s1.getRow(0).getCell(0).getCellStyle().getFontIndexAsInt();
         Font fnt = wb2.getFontAt(idx);
         assertNotNull(fnt);
@@ -127,7 +133,7 @@ public abstract class BaseTestFont {
         font2.setFontHeightInPoints((short)15);
         int font2Idx = font2.getIndexAsInt();
         wb2.createCellStyle().setFont(font2);
-        assertEquals(num0 + 2, wb2.getNumberOfFontsAsInt());
+        assertEquals(num0 + 2, wb2.getNumberOfFonts());
 
         // Save and re-load
         Workbook wb3 = _testDataProvider.writeOutAndReadBack(wb2);
@@ -135,7 +141,7 @@ public abstract class BaseTestFont {
         s1 = wb3.getSheetAt(0);
         assertNotNull(s1);
 
-        assertEquals(num0 + 2, wb3.getNumberOfFontsAsInt());
+        assertEquals(num0 + 2, wb3.getNumberOfFonts());
         assertNotNull(wb3.getFontAt(font1Idx));
         assertNotNull(wb3.getFontAt(font2Idx));
 
@@ -150,7 +156,7 @@ public abstract class BaseTestFont {
     @Test
     public final void test45338() throws IOException {
         Workbook wb = _testDataProvider.createWorkbook();
-        int num0 = wb.getNumberOfFontsAsInt();
+        int num0 = wb.getNumberOfFonts();
 
         Sheet s = wb.createSheet();
         s.createRow(0);
@@ -178,7 +184,7 @@ public abstract class BaseTestFont {
 
         Font nf = wb.createFont();
         int nfIdx = nf.getIndexAsInt();
-        assertEquals(num0 + 1, wb.getNumberOfFontsAsInt());
+        assertEquals(num0 + 1, wb.getNumberOfFonts());
 
         assertSame(nf, wb.getFontAt(nfIdx));
 
@@ -191,7 +197,7 @@ public abstract class BaseTestFont {
         nf.setTypeOffset((short)2);
         nf.setUnderline((byte)2);
 
-        assertEquals(num0 + 1, wb.getNumberOfFontsAsInt());
+        assertEquals(num0 + 1, wb.getNumberOfFonts());
         assertEquals(nf, wb.getFontAt(nfIdx));
 
         assertEquals(wb.getFontAt(nfIdx), wb.getFontAt(nfIdx));
index 02930a99593b21a2f2559017e74198a90414d142..2af30226170f72ee099abcc6b8e9a9c6f75d7912 100644 (file)
 
 package org.apache.poi.ss.usermodel;
 
+import static org.apache.poi.POITestCase.assertBetween;
+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.assertSame;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
 import org.apache.poi.common.usermodel.HyperlinkType;
 import org.apache.poi.ss.ITestDataProvider;
 import org.apache.poi.ss.SpreadsheetVersion;
 import org.apache.poi.ss.util.CellAddress;
 import org.apache.poi.ss.util.CellRangeAddress;
 import org.apache.poi.ss.util.PaneInformation;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
-
-import java.io.IOException;
-import java.util.*;
-import java.util.Map.Entry;
-
-import static org.apache.poi.POITestCase.assertBetween;
-import static org.junit.Assert.*;
-import static org.junit.Assume.assumeTrue;
 
 /**
  * Common superclass for testing {@link org.apache.poi.hssf.usermodel.HSSFCell},
@@ -43,160 +54,150 @@ import static org.junit.Assume.assumeTrue;
 public abstract class BaseTestSheet {
     private static final int ROW_COUNT = 40000;
 
-    @Rule
-    public ExpectedException thrown = ExpectedException.none();
-    
     protected final ITestDataProvider _testDataProvider;
 
     protected BaseTestSheet(ITestDataProvider testDataProvider) {
         _testDataProvider = testDataProvider;
     }
-    
+
     protected void trackColumnsForAutoSizingIfSXSSF(Sheet sheet) {
         // do nothing for Sheet base class. This will be overridden for SXSSFSheets.
     }
 
     @Test
     public void createRow() throws IOException {
-        Workbook workbook = _testDataProvider.createWorkbook();
-        Sheet sheet = workbook.createSheet();
-        assertEquals(0, sheet.getPhysicalNumberOfRows());
-
-        //Test that we get null for undefined rownumber
-        assertNull(sheet.getRow(1));
-
-        // Test row creation with consecutive indexes
-        Row row1 = sheet.createRow(0);
-        Row row2 = sheet.createRow(1);
-        assertEquals(0, row1.getRowNum());
-        assertEquals(1, row2.getRowNum());
-        Iterator<Row> it = sheet.rowIterator();
-        assertTrue(it.hasNext());
-        assertSame(row1, it.next());
-        assertTrue(it.hasNext());
-        assertSame(row2, it.next());
-        assertEquals(1, sheet.getLastRowNum());
-
-        // Test row creation with non consecutive index
-        Row row101 = sheet.createRow(100);
-        assertNotNull(row101);
-        assertEquals(100, sheet.getLastRowNum());
-        assertEquals(3, sheet.getPhysicalNumberOfRows());
-
-        // Test overwriting an existing row
-        Row row2_ovrewritten = sheet.createRow(1);
-        Cell cell = row2_ovrewritten.createCell(0);
-        cell.setCellValue(100);
-        Iterator<Row> it2 = sheet.rowIterator();
-        assertTrue(it2.hasNext());
-        assertSame(row1, it2.next());
-        assertTrue(it2.hasNext());
-        Row row2_ovrewritten_ref = it2.next();
-        assertSame(row2_ovrewritten, row2_ovrewritten_ref);
-        assertEquals(100.0, row2_ovrewritten_ref.getCell(0).getNumericCellValue(), 0.0);
-        
-        workbook.close();
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            Sheet sheet = workbook.createSheet();
+            assertEquals(0, sheet.getPhysicalNumberOfRows());
+
+            //Test that we get null for undefined rownumber
+            assertNull(sheet.getRow(1));
+
+            // Test row creation with consecutive indexes
+            Row row1 = sheet.createRow(0);
+            Row row2 = sheet.createRow(1);
+            assertEquals(0, row1.getRowNum());
+            assertEquals(1, row2.getRowNum());
+            Iterator<Row> it = sheet.rowIterator();
+            assertTrue(it.hasNext());
+            assertSame(row1, it.next());
+            assertTrue(it.hasNext());
+            assertSame(row2, it.next());
+            assertEquals(1, sheet.getLastRowNum());
+
+            // Test row creation with non consecutive index
+            Row row101 = sheet.createRow(100);
+            assertNotNull(row101);
+            assertEquals(100, sheet.getLastRowNum());
+            assertEquals(3, sheet.getPhysicalNumberOfRows());
+
+            // Test overwriting an existing row
+            Row row2_ovrewritten = sheet.createRow(1);
+            Cell cell = row2_ovrewritten.createCell(0);
+            cell.setCellValue(100);
+            Iterator<Row> it2 = sheet.rowIterator();
+            assertTrue(it2.hasNext());
+            assertSame(row1, it2.next());
+            assertTrue(it2.hasNext());
+            Row row2_ovrewritten_ref = it2.next();
+            assertSame(row2_ovrewritten, row2_ovrewritten_ref);
+            assertEquals(100.0, row2_ovrewritten_ref.getCell(0).getNumericCellValue(), 0.0);
+        }
     }
-    
+
     @Test(expected=IllegalArgumentException.class)
     public void createRowBeforeFirstRow() throws IOException {
-        final Workbook workbook = _testDataProvider.createWorkbook();
-        final Sheet sh = workbook.createSheet();
-        sh.createRow(0);
-        try {
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            final Sheet sh = workbook.createSheet();
+            sh.createRow(0);
             // Negative rows not allowed
             sh.createRow(-1);
-        } finally {
-            workbook.close();
         }
     }
-    
+
     @Test(expected=IllegalArgumentException.class)
     public void createRowAfterLastRow() throws IOException {
         final SpreadsheetVersion version = _testDataProvider.getSpreadsheetVersion();
-        final Workbook workbook = _testDataProvider.createWorkbook();
-        final Sheet sh = workbook.createSheet();
-        sh.createRow(version.getLastRowIndex());
-        try {
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            final Sheet sh = workbook.createSheet();
+            sh.createRow(version.getLastRowIndex());
             // Row number must be between 0 and last row
             sh.createRow(version.getLastRowIndex() + 1);
-        } finally {
-            workbook.close();
         }
     }
 
     @Test
     public void removeRow() throws IOException {
-        Workbook workbook = _testDataProvider.createWorkbook();
-        Sheet sheet1 = workbook.createSheet();
-        assertEquals(0, sheet1.getPhysicalNumberOfRows());
-        assertEquals(-1, sheet1.getFirstRowNum());
-        assertEquals(-1, sheet1.getLastRowNum());
-
-        Row row0 = sheet1.createRow(0);
-        assertEquals(1, sheet1.getPhysicalNumberOfRows());
-        assertEquals(0, sheet1.getFirstRowNum());
-        assertEquals(0, sheet1.getLastRowNum());
-        sheet1.removeRow(row0);
-        assertEquals(0, sheet1.getPhysicalNumberOfRows());
-        assertEquals(-1, sheet1.getFirstRowNum());
-        assertEquals(-1, sheet1.getLastRowNum());
-
-        sheet1.createRow(1);
-        Row row2 = sheet1.createRow(2);
-        assertEquals(2, sheet1.getPhysicalNumberOfRows());
-        assertEquals(1, sheet1.getFirstRowNum());
-        assertEquals(2, sheet1.getLastRowNum());
-
-        assertNotNull(sheet1.getRow(1));
-        assertNotNull(sheet1.getRow(2));
-        sheet1.removeRow(row2);
-        assertNotNull(sheet1.getRow(1));
-        assertNull(sheet1.getRow(2));
-        assertEquals(1, sheet1.getPhysicalNumberOfRows());
-        assertEquals(1, sheet1.getFirstRowNum());
-        assertEquals(1, sheet1.getLastRowNum());
-
-        Row row3 = sheet1.createRow(3);
-        Sheet sheet2 = workbook.createSheet();
-
-        thrown.expect(IllegalArgumentException.class);
-        thrown.expectMessage("Specified row does not belong to this sheet");
-        sheet2.removeRow(row3);
-
-        workbook.close();
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            Sheet sheet1 = workbook.createSheet();
+            assertEquals(0, sheet1.getPhysicalNumberOfRows());
+            assertEquals(-1, sheet1.getFirstRowNum());
+            assertEquals(-1, sheet1.getLastRowNum());
+
+            Row row0 = sheet1.createRow(0);
+            assertEquals(1, sheet1.getPhysicalNumberOfRows());
+            assertEquals(0, sheet1.getFirstRowNum());
+            assertEquals(0, sheet1.getLastRowNum());
+            sheet1.removeRow(row0);
+            assertEquals(0, sheet1.getPhysicalNumberOfRows());
+            assertEquals(-1, sheet1.getFirstRowNum());
+            assertEquals(-1, sheet1.getLastRowNum());
+
+            sheet1.createRow(1);
+            Row row2 = sheet1.createRow(2);
+            assertEquals(2, sheet1.getPhysicalNumberOfRows());
+            assertEquals(1, sheet1.getFirstRowNum());
+            assertEquals(2, sheet1.getLastRowNum());
+
+            assertNotNull(sheet1.getRow(1));
+            assertNotNull(sheet1.getRow(2));
+            sheet1.removeRow(row2);
+            assertNotNull(sheet1.getRow(1));
+            assertNull(sheet1.getRow(2));
+            assertEquals(1, sheet1.getPhysicalNumberOfRows());
+            assertEquals(1, sheet1.getFirstRowNum());
+            assertEquals(1, sheet1.getLastRowNum());
+
+            Row row3 = sheet1.createRow(3);
+            Sheet sheet2 = workbook.createSheet();
+
+            IllegalArgumentException ex = assertThrows(
+                IllegalArgumentException.class,
+                () -> sheet2.removeRow(row3)
+            );
+            assertEquals("Specified row does not belong to this sheet", ex.getMessage());
+        }
     }
 
     @Test
     public void cloneSheet() throws IOException {
-        Workbook workbook = _testDataProvider.createWorkbook();
-        CreationHelper factory = workbook.getCreationHelper();
-        Sheet sheet = workbook.createSheet("Test Clone");
-        Row row = sheet.createRow(0);
-        Cell cell = row.createCell(0);
-        Cell cell2 = row.createCell(1);
-        cell.setCellValue(factory.createRichTextString("clone_test"));
-        cell2.setCellFormula("SIN(1)");
-
-        Sheet clonedSheet = workbook.cloneSheet(0);
-        Row clonedRow = clonedSheet.getRow(0);
-
-        //Check for a good clone
-        assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test");
-
-        //Check that the cells are not somehow linked
-        cell.setCellValue(factory.createRichTextString("Difference Check"));
-        cell2.setCellFormula("cos(2)");
-        if ("Difference Check".equals(clonedRow.getCell(0).getRichStringCellValue().getString())) {
-            fail("string cell not properly cloned");
-        }
-        if ("COS(2)".equals(clonedRow.getCell(1).getCellFormula())) {
-            fail("formula cell not properly cloned");
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            CreationHelper factory = workbook.getCreationHelper();
+            Sheet sheet = workbook.createSheet("Test Clone");
+            Row row = sheet.createRow(0);
+            Cell cell = row.createCell(0);
+            Cell cell2 = row.createCell(1);
+            cell.setCellValue(factory.createRichTextString("clone_test"));
+            cell2.setCellFormula("SIN(1)");
+
+            Sheet clonedSheet = workbook.cloneSheet(0);
+            Row clonedRow = clonedSheet.getRow(0);
+
+            //Check for a good clone
+            assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test");
+
+            //Check that the cells are not somehow linked
+            cell.setCellValue(factory.createRichTextString("Difference Check"));
+            cell2.setCellFormula("cos(2)");
+            if ("Difference Check".equals(clonedRow.getCell(0).getRichStringCellValue().getString())) {
+                fail("string cell not properly cloned");
+            }
+            if ("COS(2)".equals(clonedRow.getCell(1).getCellFormula())) {
+                fail("formula cell not properly cloned");
+            }
+            assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test");
+            assertEquals(clonedRow.getCell(1).getCellFormula(), "SIN(1)");
         }
-        assertEquals(clonedRow.getCell(0).getRichStringCellValue().getString(), "clone_test");
-        assertEquals(clonedRow.getCell(1).getCellFormula(), "SIN(1)");
-        
-        workbook.close();
     }
 
     /** tests that the sheet name for multiple clones of the same sheet is unique
@@ -204,29 +205,28 @@ public abstract class BaseTestSheet {
      */
     @Test
     public void cloneSheetMultipleTimes() throws IOException {
-        Workbook workbook = _testDataProvider.createWorkbook();
-        CreationHelper factory = workbook.getCreationHelper();
-        Sheet sheet = workbook.createSheet("Test Clone");
-        Row row = sheet.createRow(0);
-        Cell cell = row.createCell(0);
-        cell.setCellValue(factory.createRichTextString("clone_test"));
-        //Clone the sheet multiple times
-        workbook.cloneSheet(0);
-        workbook.cloneSheet(0);
-
-        assertNotNull(workbook.getSheet("Test Clone"));
-        assertNotNull(workbook.getSheet("Test Clone (2)"));
-        assertEquals("Test Clone (3)", workbook.getSheetName(2));
-        assertNotNull(workbook.getSheet("Test Clone (3)"));
-
-        workbook.removeSheetAt(0);
-        workbook.removeSheetAt(0);
-        workbook.removeSheetAt(0);
-        workbook.createSheet("abc ( 123)");
-        workbook.cloneSheet(0);
-        assertEquals("abc (124)", workbook.getSheetName(1));
-        
-        workbook.close();
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            CreationHelper factory = workbook.getCreationHelper();
+            Sheet sheet = workbook.createSheet("Test Clone");
+            Row row = sheet.createRow(0);
+            Cell cell = row.createCell(0);
+            cell.setCellValue(factory.createRichTextString("clone_test"));
+            //Clone the sheet multiple times
+            workbook.cloneSheet(0);
+            workbook.cloneSheet(0);
+
+            assertNotNull(workbook.getSheet("Test Clone"));
+            assertNotNull(workbook.getSheet("Test Clone (2)"));
+            assertEquals("Test Clone (3)", workbook.getSheetName(2));
+            assertNotNull(workbook.getSheet("Test Clone (3)"));
+
+            workbook.removeSheetAt(0);
+            workbook.removeSheetAt(0);
+            workbook.removeSheetAt(0);
+            workbook.createSheet("abc ( 123)");
+            workbook.cloneSheet(0);
+            assertEquals("abc (124)", workbook.getSheetName(1));
+        }
     }
 
     /**
@@ -234,91 +234,86 @@ public abstract class BaseTestSheet {
      */
     @Test
     public void printSetupLandscapeNew() throws IOException {
-        Workbook wb1 = _testDataProvider.createWorkbook();
-        Sheet sheetL = wb1.createSheet("LandscapeS");
-        Sheet sheetP = wb1.createSheet("LandscapeP");
-
-        // Check two aspects of the print setup
-        assertFalse(sheetL.getPrintSetup().getLandscape());
-        assertFalse(sheetP.getPrintSetup().getLandscape());
-        assertEquals(1, sheetL.getPrintSetup().getCopies());
-        assertEquals(1, sheetP.getPrintSetup().getCopies());
-
-        // Change one on each
-        sheetL.getPrintSetup().setLandscape(true);
-        sheetP.getPrintSetup().setCopies((short)3);
-
-        // Check taken
-        assertTrue(sheetL.getPrintSetup().getLandscape());
-        assertFalse(sheetP.getPrintSetup().getLandscape());
-        assertEquals(1, sheetL.getPrintSetup().getCopies());
-        assertEquals(3, sheetP.getPrintSetup().getCopies());
-
-        // Save and re-load, and check still there
-        Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
-        wb1.close();
-        sheetL = wb2.getSheet("LandscapeS");
-        sheetP = wb2.getSheet("LandscapeP");
-
-        assertTrue(sheetL.getPrintSetup().getLandscape());
-        assertFalse(sheetP.getPrintSetup().getLandscape());
-        assertEquals(1, sheetL.getPrintSetup().getCopies());
-        assertEquals(3, sheetP.getPrintSetup().getCopies());
-        wb2.close();
+        try (Workbook wb1 = _testDataProvider.createWorkbook()) {
+            Sheet sheetL = wb1.createSheet("LandscapeS");
+            Sheet sheetP = wb1.createSheet("LandscapeP");
+
+            // Check two aspects of the print setup
+            assertFalse(sheetL.getPrintSetup().getLandscape());
+            assertFalse(sheetP.getPrintSetup().getLandscape());
+            assertEquals(1, sheetL.getPrintSetup().getCopies());
+            assertEquals(1, sheetP.getPrintSetup().getCopies());
+
+            // Change one on each
+            sheetL.getPrintSetup().setLandscape(true);
+            sheetP.getPrintSetup().setCopies((short) 3);
+
+            // Check taken
+            assertTrue(sheetL.getPrintSetup().getLandscape());
+            assertFalse(sheetP.getPrintSetup().getLandscape());
+            assertEquals(1, sheetL.getPrintSetup().getCopies());
+            assertEquals(3, sheetP.getPrintSetup().getCopies());
+
+            // Save and re-load, and check still there
+            try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
+                sheetL = wb2.getSheet("LandscapeS");
+                sheetP = wb2.getSheet("LandscapeP");
+
+                assertTrue(sheetL.getPrintSetup().getLandscape());
+                assertFalse(sheetP.getPrintSetup().getLandscape());
+                assertEquals(1, sheetL.getPrintSetup().getCopies());
+                assertEquals(3, sheetP.getPrintSetup().getCopies());
+            }
+        }
     }
-    
+
     /**
      * Disallow creating wholly or partially overlapping merged regions
      * as this results in a corrupted workbook
      */
     @Test
     public void addOverlappingMergedRegions() throws IOException {
-        final Workbook wb = _testDataProvider.createWorkbook();
-        final Sheet sheet = wb.createSheet();
-        
-        final CellRangeAddress baseRegion = new CellRangeAddress(0, 1, 0, 1); //A1:B2
-        assertEquals(0, sheet.addMergedRegion(baseRegion));
-        
-        try {
+        try (final Workbook wb = _testDataProvider.createWorkbook()) {
+            final Sheet sheet = wb.createSheet();
+
+            final CellRangeAddress baseRegion = new CellRangeAddress(0, 1, 0, 1); //A1:B2
+            assertEquals(0, sheet.addMergedRegion(baseRegion));
+
             final CellRangeAddress duplicateRegion = new CellRangeAddress(0, 1, 0, 1); //A1:B2
-            sheet.addMergedRegion(duplicateRegion);
-            fail("Should not be able to add a merged region (" + duplicateRegion.formatAsString() + ") " +
-                 "if sheet already contains the same merged region (" + baseRegion.formatAsString() + ")");
-        } catch (final IllegalStateException e) {
-            // expected here
-        }
-        
-        try {
+            assertThrows(
+                "Should not be able to add a merged region (" + duplicateRegion.formatAsString() + ") " +
+                "if sheet already contains the same merged region (" + baseRegion.formatAsString() + ")",
+                IllegalStateException.class,
+                () -> sheet.addMergedRegion(duplicateRegion)
+            );
+
             final CellRangeAddress partiallyOverlappingRegion = new CellRangeAddress(1, 2, 1, 2); //B2:C3
-            sheet.addMergedRegion(partiallyOverlappingRegion);
-            fail("Should not be able to add a merged region (" + partiallyOverlappingRegion.formatAsString() + ") " +
-                 "if it partially overlaps with an existing merged region (" + baseRegion.formatAsString() + ")");
-        } catch (final IllegalStateException e) {
-            // expected here
-        }
-        
-        try {
+            assertThrows(
+                "Should not be able to add a merged region (" + partiallyOverlappingRegion.formatAsString() + ") " +
+                "if it partially overlaps with an existing merged region (" + baseRegion.formatAsString() + ")",
+                IllegalStateException.class,
+                () -> sheet.addMergedRegion(partiallyOverlappingRegion)
+            );
+
             final CellRangeAddress subsetRegion = new CellRangeAddress(0, 1, 0, 0); //A1:A2
-            sheet.addMergedRegion(subsetRegion);
-            fail("Should not be able to add a merged region (" + subsetRegion.formatAsString() + ") " +
-                 "if it is a formal subset of an existing merged region (" + baseRegion.formatAsString() + ")");
-        } catch (final IllegalStateException e) {
-            // expected here
-        }
-        
-        try {
+            assertThrows(
+                "Should not be able to add a merged region (" + subsetRegion.formatAsString() + ") " +
+                "if it is a formal subset of an existing merged region (" + baseRegion.formatAsString() + ")",
+                IllegalStateException.class,
+                () -> sheet.addMergedRegion(subsetRegion)
+            );
+
             final CellRangeAddress supersetRegion = new CellRangeAddress(0, 2, 0, 2); //A1:C3
-            sheet.addMergedRegion(supersetRegion);
-            fail("Should not be able to add a merged region (" + supersetRegion.formatAsString() + ") " +
-                 "if it is a formal superset of an existing merged region (" + baseRegion.formatAsString() + ")");
-        } catch (final IllegalStateException e) {
-            // expected here
+            assertThrows(
+                "Should not be able to add a merged region (" + supersetRegion.formatAsString() + ") " +
+                "if it is a formal superset of an existing merged region (" + baseRegion.formatAsString() + ")",
+                IllegalStateException.class,
+                () -> sheet.addMergedRegion(supersetRegion)
+            );
+
+            final CellRangeAddress disjointRegion = new CellRangeAddress(10, 11, 10, 11);
+            assertEquals(1, sheet.addMergedRegion(disjointRegion));
         }
-        
-        final CellRangeAddress disjointRegion = new CellRangeAddress(10, 11, 10, 11);
-        assertEquals(1, sheet.addMergedRegion(disjointRegion));
-        
-        wb.close();
     }
 
     /*
@@ -326,17 +321,16 @@ public abstract class BaseTestSheet {
      */
     @Test
     public void addMergedRegionWithSingleCellShouldFail() throws IOException {
-        final Workbook wb = _testDataProvider.createWorkbook();
-
-        final Sheet sheet = wb.createSheet();
-        final CellRangeAddress region = CellRangeAddress.valueOf("A1:A1");
-        try {
-            sheet.addMergedRegion(region);
-            fail("Should not be able to add a single-cell merged region (" + region.formatAsString() + ")");
-        } catch (final IllegalArgumentException e) {
-            // expected
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+
+            final Sheet sheet = wb.createSheet();
+            final CellRangeAddress region = CellRangeAddress.valueOf("A1:A1");
+            assertThrows(
+                "Should not be able to add a single-cell merged region (" + region.formatAsString() + ")",
+                IllegalArgumentException.class,
+                () -> sheet.addMergedRegion(region)
+            );
         }
-        wb.close();
     }
 
     /**
@@ -346,39 +340,35 @@ public abstract class BaseTestSheet {
      */
     @Test
     public void addMerged() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet = wb.createSheet();
-        assertEquals(0, sheet.getNumMergedRegions());
-        SpreadsheetVersion ssVersion = _testDataProvider.getSpreadsheetVersion();
-
-        CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1);
-        assertEquals(0, sheet.addMergedRegion(region));
-        assertEquals(1, sheet.getNumMergedRegions());
-
-        try {
-            region = new CellRangeAddress(-1, -1, -1, -1);
-            sheet.addMergedRegion(region);
-            fail("Expected exception");
-        } catch (IllegalArgumentException e){
-            // TODO: assertEquals("Minimum row number is 0.", e.getMessage());
-        }
-        try {
-            region = new CellRangeAddress(0, 0, 0, ssVersion.getLastColumnIndex() + 1);
-            sheet.addMergedRegion(region);
-            fail("Expected exception");
-        } catch (IllegalArgumentException e){
-            assertEquals("Maximum column number is " + ssVersion.getLastColumnIndex(), e.getMessage());
-        }
-        try {
-            region = new CellRangeAddress(0, ssVersion.getLastRowIndex() + 1, 0, 1);
-            sheet.addMergedRegion(region);
-            fail("Expected exception");
-        } catch (IllegalArgumentException e){
-            assertEquals("Maximum row number is " + ssVersion.getLastRowIndex(), e.getMessage());
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb.createSheet();
+            assertEquals(0, sheet.getNumMergedRegions());
+            SpreadsheetVersion ssVersion = _testDataProvider.getSpreadsheetVersion();
+
+            CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1);
+            assertEquals(0, sheet.addMergedRegion(region));
+            assertEquals(1, sheet.getNumMergedRegions());
+
+            IllegalArgumentException ex = assertThrows(
+                IllegalArgumentException.class,
+                () -> sheet.addMergedRegion(new CellRangeAddress(-1, -1, -1, -1))
+            );
+            assertEquals("Merged region : must contain 2 or more cells", ex.getMessage());
+
+            ex = assertThrows(
+                IllegalArgumentException.class,
+                () -> sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, ssVersion.getLastColumnIndex() + 1))
+            );
+            assertEquals("Maximum column number is " + ssVersion.getLastColumnIndex(), ex.getMessage());
+
+            ex = assertThrows(
+                IllegalArgumentException.class,
+                () -> sheet.addMergedRegion(new CellRangeAddress(0, ssVersion.getLastRowIndex() + 1, 0, 1))
+            );
+            assertEquals("Maximum row number is " + ssVersion.getLastRowIndex(), ex.getMessage());
+
+            assertEquals(1, sheet.getNumMergedRegions());
         }
-        assertEquals(1, sheet.getNumMergedRegions());
-        
-        wb.close();
     }
 
     /**
@@ -387,65 +377,63 @@ public abstract class BaseTestSheet {
      */
     @Test
     public void removeMerged() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet = wb.createSheet();
-        CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1);
-        assertEquals(0, sheet.addMergedRegion(region));
-        region = new CellRangeAddress(2, 3, 0, 1);
-        assertEquals(1, sheet.addMergedRegion(region));
-
-        sheet.removeMergedRegion(0);
-
-        region = sheet.getMergedRegion(0);
-        assertEquals("Left over region should be starting at row 2", 2, region.getFirstRow());
-
-        sheet.removeMergedRegion(0);
-
-        assertEquals("there should be no merged regions left!", 0, sheet.getNumMergedRegions());
-
-        //an, add, remove, get(0) would null pointer
-        assertEquals(0, sheet.addMergedRegion(region));
-        assertEquals("there should now be one merged region!", 1, sheet.getNumMergedRegions());
-        sheet.removeMergedRegion(0);
-        assertEquals("there should now be zero merged regions!", 0, sheet.getNumMergedRegions());
-        //add it again!
-        region.setLastRow(4);
-
-        assertEquals(0, sheet.addMergedRegion(region));
-        assertEquals("there should now be one merged region!", 1, sheet.getNumMergedRegions());
-
-        //should exist now!
-        assertTrue("there isn't more than one merged region in there", 1 <= sheet.getNumMergedRegions());
-        region = sheet.getMergedRegion(0);
-        assertEquals("the merged row to doesn't match the one we put in ", 4, region.getLastRow());
-        
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb.createSheet();
+            CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1);
+            assertEquals(0, sheet.addMergedRegion(region));
+            region = new CellRangeAddress(2, 3, 0, 1);
+            assertEquals(1, sheet.addMergedRegion(region));
+
+            sheet.removeMergedRegion(0);
+
+            region = sheet.getMergedRegion(0);
+            assertEquals("Left over region should be starting at row 2", 2, region.getFirstRow());
+
+            sheet.removeMergedRegion(0);
+
+            assertEquals("there should be no merged regions left!", 0, sheet.getNumMergedRegions());
+
+            //an, add, remove, get(0) would null pointer
+            assertEquals(0, sheet.addMergedRegion(region));
+            assertEquals("there should now be one merged region!", 1, sheet.getNumMergedRegions());
+            sheet.removeMergedRegion(0);
+            assertEquals("there should now be zero merged regions!", 0, sheet.getNumMergedRegions());
+            //add it again!
+            region.setLastRow(4);
+
+            assertEquals(0, sheet.addMergedRegion(region));
+            assertEquals("there should now be one merged region!", 1, sheet.getNumMergedRegions());
+
+            //should exist now!
+            assertTrue("there isn't more than one merged region in there", 1 <= sheet.getNumMergedRegions());
+            region = sheet.getMergedRegion(0);
+            assertEquals("the merged row to doesn't match the one we put in ", 4, region.getLastRow());
+        }
     }
-    
+
     /**
      * Remove multiple merged regions
      */
     @Test
     public void removeMergedRegions() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet = wb.createSheet();
-        
-        Map<Integer, CellRangeAddress> mergedRegions = new HashMap<>();
-        for (int r=0; r<10; r++) {
-            CellRangeAddress region = new CellRangeAddress(r, r, 0, 1);
-            mergedRegions.put(r, region);
-            assertEquals(r, sheet.addMergedRegion(region));
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb.createSheet();
+
+            Map<Integer, CellRangeAddress> mergedRegions = new HashMap<>();
+            for (int r = 0; r < 10; r++) {
+                CellRangeAddress region = new CellRangeAddress(r, r, 0, 1);
+                mergedRegions.put(r, region);
+                assertEquals(r, sheet.addMergedRegion(region));
+            }
+            assertCollectionEquals(mergedRegions.values(), sheet.getMergedRegions());
+
+            Collection<Integer> removed = Arrays.asList(0, 2, 3, 6, 8);
+            mergedRegions.keySet().removeAll(removed);
+            sheet.removeMergedRegions(removed);
+            assertCollectionEquals(mergedRegions.values(), sheet.getMergedRegions());
         }
-        assertCollectionEquals(mergedRegions.values(), sheet.getMergedRegions());
-        
-        Collection<Integer> removed = Arrays.asList(0, 2, 3, 6, 8);
-        mergedRegions.keySet().removeAll(removed);
-        sheet.removeMergedRegions(removed);
-        assertCollectionEquals(mergedRegions.values(), sheet.getMergedRegions());
-        
-        wb.close();
     }
-    
+
     private static <T> void assertCollectionEquals(Collection<T> expected, Collection<T> actual) {
         Set<T> e = new HashSet<>(expected);
         Set<T> a = new HashSet<>(actual);
@@ -454,28 +442,27 @@ public abstract class BaseTestSheet {
 
     @Test
     public void shiftMerged() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        CreationHelper factory = wb.getCreationHelper();
-        Sheet sheet = wb.createSheet();
-        Row row = sheet.createRow(0);
-        Cell cell = row.createCell(0);
-        cell.setCellValue(factory.createRichTextString("first row, first cell"));
-
-        row = sheet.createRow(1);
-        cell = row.createCell(1);
-        cell.setCellValue(factory.createRichTextString("second row, second cell"));
-
-        CellRangeAddress region = CellRangeAddress.valueOf("A2:B2");
-        assertEquals(0, sheet.addMergedRegion(region));
-
-        sheet.shiftRows(1, 1, 1);
-
-        region = sheet.getMergedRegion(0);
-        
-        CellRangeAddress expectedRegion = CellRangeAddress.valueOf("A3:B3");
-        assertEquals("Merged region should shift down a row", expectedRegion, region);
-        
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            CreationHelper factory = wb.getCreationHelper();
+            Sheet sheet = wb.createSheet();
+            Row row = sheet.createRow(0);
+            Cell cell = row.createCell(0);
+            cell.setCellValue(factory.createRichTextString("first row, first cell"));
+
+            row = sheet.createRow(1);
+            cell = row.createCell(1);
+            cell.setCellValue(factory.createRichTextString("second row, second cell"));
+
+            CellRangeAddress region = CellRangeAddress.valueOf("A2:B2");
+            assertEquals(0, sheet.addMergedRegion(region));
+
+            sheet.shiftRows(1, 1, 1);
+
+            region = sheet.getMergedRegion(0);
+
+            CellRangeAddress expectedRegion = CellRangeAddress.valueOf("A3:B3");
+            assertEquals("Merged region should shift down a row", expectedRegion, region);
+        }
     }
 
     /**
@@ -486,44 +473,42 @@ public abstract class BaseTestSheet {
      */
     @Test
     public void addMergedRegionUnsafe() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sh = wb.createSheet();
-        CellRangeAddress region1 = CellRangeAddress.valueOf("A1:B2");
-        CellRangeAddress region2 = CellRangeAddress.valueOf("B2:C3");
-        CellRangeAddress region3 = CellRangeAddress.valueOf("C3:D4");
-        CellRangeAddress region4 = CellRangeAddress.valueOf("J10:K11");
-        assumeTrue(region1.intersects(region2));
-        assumeTrue(region2.intersects(region3));
-
-        assertEquals(0, sh.addMergedRegionUnsafe(region1));
-        assertTrue(sh.getMergedRegions().contains(region1));
-
-        // adding a duplicate or overlapping merged region should not
-        // raise an exception with the unsafe version of addMergedRegion.
-
-        assertEquals(1, sh.addMergedRegionUnsafe(region2));
-
-        // the safe version of addMergedRegion should throw when trying to add a merged region that overlaps an existing region
-        assertTrue(sh.getMergedRegions().contains(region2));
-        try {
-            sh.addMergedRegion(region3);
-            fail("Expected IllegalStateException. region3 overlaps already added merged region2.");
-        } catch (final IllegalStateException e) {
-            // expected
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sh = wb.createSheet();
+            CellRangeAddress region1 = CellRangeAddress.valueOf("A1:B2");
+            CellRangeAddress region2 = CellRangeAddress.valueOf("B2:C3");
+            CellRangeAddress region3 = CellRangeAddress.valueOf("C3:D4");
+            CellRangeAddress region4 = CellRangeAddress.valueOf("J10:K11");
+            assumeTrue(region1.intersects(region2));
+            assumeTrue(region2.intersects(region3));
+
+            assertEquals(0, sh.addMergedRegionUnsafe(region1));
+            assertTrue(sh.getMergedRegions().contains(region1));
+
+            // adding a duplicate or overlapping merged region should not
+            // raise an exception with the unsafe version of addMergedRegion.
+
+            assertEquals(1, sh.addMergedRegionUnsafe(region2));
+
+            // the safe version of addMergedRegion should throw when trying to add a merged region that overlaps an existing region
+            assertTrue(sh.getMergedRegions().contains(region2));
+            assertThrows(
+                "region3 overlaps already added merged region2.",
+                IllegalStateException.class,
+                () -> sh.addMergedRegion(region3)
+            );
             assertFalse(sh.getMergedRegions().contains(region3));
-        }
-        // addMergedRegion should not re-validate previously-added merged regions
-        assertEquals(2, sh.addMergedRegion(region4));
-
-        // validation methods should detect a problem with previously added merged regions (runs in O(n^2) time)
-        try {
-            sh.validateMergedRegions();
-            fail("Expected validation to fail. Sheet contains merged regions A1:B2 and B2:C3, which overlap at B2.");
-        } catch (final IllegalStateException e) {
-            // expected
-        }
 
-        wb.close();
+            // addMergedRegion should not re-validate previously-added merged regions
+            assertEquals(2, sh.addMergedRegion(region4));
+
+            // validation methods should detect a problem with previously added merged regions (runs in O(n^2) time)
+            assertThrows(
+                "Sheet contains merged regions A1:B2 and B2:C3, which overlap at B2.",
+                IllegalStateException.class,
+                sh::validateMergedRegions
+            );
+        }
     }
 
     /**
@@ -531,187 +516,181 @@ public abstract class BaseTestSheet {
      */
     @Test
     public void displayOptions() throws IOException {
-        Workbook wb1 = _testDataProvider.createWorkbook();
-        Sheet sheet = wb1.createSheet();
-
-        assertTrue(sheet.isDisplayGridlines());
-        assertTrue(sheet.isDisplayRowColHeadings());
-        assertFalse(sheet.isDisplayFormulas());
-        assertTrue(sheet.isDisplayZeros());
-
-        sheet.setDisplayGridlines(false);
-        sheet.setDisplayRowColHeadings(false);
-        sheet.setDisplayFormulas(true);
-        sheet.setDisplayZeros(false);
-
-        Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
-        wb1.close();
-        sheet = wb2.getSheetAt(0);
-
-        assertFalse(sheet.isDisplayGridlines());
-        assertFalse(sheet.isDisplayRowColHeadings());
-        assertTrue(sheet.isDisplayFormulas());
-        assertFalse(sheet.isDisplayZeros());
-        
-        wb2.close();
+        try (Workbook wb1 = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb1.createSheet();
+
+            assertTrue(sheet.isDisplayGridlines());
+            assertTrue(sheet.isDisplayRowColHeadings());
+            assertFalse(sheet.isDisplayFormulas());
+            assertTrue(sheet.isDisplayZeros());
+
+            sheet.setDisplayGridlines(false);
+            sheet.setDisplayRowColHeadings(false);
+            sheet.setDisplayFormulas(true);
+            sheet.setDisplayZeros(false);
+
+            try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
+                sheet = wb2.getSheetAt(0);
+
+                assertFalse(sheet.isDisplayGridlines());
+                assertFalse(sheet.isDisplayRowColHeadings());
+                assertTrue(sheet.isDisplayFormulas());
+                assertFalse(sheet.isDisplayZeros());
+            }
+        }
     }
 
     @Test
     public void columnWidth() throws IOException {
-        Workbook wb1 = _testDataProvider.createWorkbook();
-        Sheet sheet = wb1.createSheet();
-
-        //default column width measured in characters
-        sheet.setDefaultColumnWidth(10);
-        assertEquals(10, sheet.getDefaultColumnWidth());
-        //columns A-C have default width
-        assertEquals(256*10, sheet.getColumnWidth(0));
-        assertEquals(256*10, sheet.getColumnWidth(1));
-        assertEquals(256*10, sheet.getColumnWidth(2));
-
-        //set custom width for D-F
-        for (char i = 'D'; i <= 'F'; i++) {
-            //Sheet#setColumnWidth accepts the width in units of 1/256th of a character width
-            int w = 256*12;
-            sheet.setColumnWidth(i, w);
-            assertEquals(w, sheet.getColumnWidth(i));
-        }
-        //reset the default column width, columns A-C change, D-F still have custom width
-        sheet.setDefaultColumnWidth(20);
-        assertEquals(20, sheet.getDefaultColumnWidth());
-        assertEquals(256*20, sheet.getColumnWidth(0));
-        assertEquals(256*20, sheet.getColumnWidth(1));
-        assertEquals(256*20, sheet.getColumnWidth(2));
-        for (char i = 'D'; i <= 'F'; i++) {
-            int w = 256*12;
-            assertEquals(w, sheet.getColumnWidth(i));
-        }
-
-        // check for 16-bit signed/unsigned error:
-        sheet.setColumnWidth(10, 40000);
-        assertEquals(40000, sheet.getColumnWidth(10));
-
-        //The maximum column width for an individual cell is 255 characters
-        try {
-            sheet.setColumnWidth(9, 256*256);
-            fail("expected exception");
-        } catch(IllegalArgumentException e){
-            assertEquals("The maximum column width for an individual cell is 255 characters.", e.getMessage());
-        }
+        try (Workbook wb1 = _testDataProvider.createWorkbook()) {
+            Sheet sheet1 = wb1.createSheet();
+
+            //default column width measured in characters
+            sheet1.setDefaultColumnWidth(10);
+            assertEquals(10, sheet1.getDefaultColumnWidth());
+            //columns A-C have default width
+            assertEquals(256 * 10, sheet1.getColumnWidth(0));
+            assertEquals(256 * 10, sheet1.getColumnWidth(1));
+            assertEquals(256 * 10, sheet1.getColumnWidth(2));
+
+            //set custom width for D-F
+            for (char i = 'D'; i <= 'F'; i++) {
+                //Sheet#setColumnWidth accepts the width in units of 1/256th of a character width
+                int w = 256 * 12;
+                sheet1.setColumnWidth(i, w);
+                assertEquals(w, sheet1.getColumnWidth(i));
+            }
+            //reset the default column width, columns A-C change, D-F still have custom width
+            sheet1.setDefaultColumnWidth(20);
+            assertEquals(20, sheet1.getDefaultColumnWidth());
+            assertEquals(256 * 20, sheet1.getColumnWidth(0));
+            assertEquals(256 * 20, sheet1.getColumnWidth(1));
+            assertEquals(256 * 20, sheet1.getColumnWidth(2));
+            for (char i = 'D'; i <= 'F'; i++) {
+                int w = 256 * 12;
+                assertEquals(w, sheet1.getColumnWidth(i));
+            }
 
-        //serialize and read again
-        Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
-        wb1.close();
-
-        sheet = wb2.getSheetAt(0);
-        assertEquals(20, sheet.getDefaultColumnWidth());
-        //columns A-C have default width
-        assertEquals(256*20, sheet.getColumnWidth(0));
-        assertEquals(256*20, sheet.getColumnWidth(1));
-        assertEquals(256*20, sheet.getColumnWidth(2));
-        //columns D-F have custom width
-        for (char i = 'D'; i <= 'F'; i++) {
-            short w = (256*12);
-            assertEquals(w, sheet.getColumnWidth(i));
+            // check for 16-bit signed/unsigned error:
+            sheet1.setColumnWidth(10, 40000);
+            assertEquals(40000, sheet1.getColumnWidth(10));
+
+            //The maximum column width for an individual cell is 255 characters
+            IllegalArgumentException ex = assertThrows(
+                IllegalArgumentException.class,
+                () -> sheet1.setColumnWidth(9, 256 * 256)
+            );
+            assertEquals("The maximum column width for an individual cell is 255 characters.", ex.getMessage());
+
+            //serialize and read again
+            try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
+                Sheet sheet2 = wb2.getSheetAt(0);
+                assertEquals(20, sheet2.getDefaultColumnWidth());
+                //columns A-C have default width
+                assertEquals(256 * 20, sheet2.getColumnWidth(0));
+                assertEquals(256 * 20, sheet2.getColumnWidth(1));
+                assertEquals(256 * 20, sheet2.getColumnWidth(2));
+                //columns D-F have custom width
+                for (char i = 'D'; i <= 'F'; i++) {
+                    short w = (256 * 12);
+                    assertEquals(w, sheet2.getColumnWidth(i));
+                }
+                assertEquals(40000, sheet2.getColumnWidth(10));
+            }
         }
-        assertEquals(40000, sheet.getColumnWidth(10));
-        
-        wb2.close();
     }
 
-    
+
     @Test
     public void defaultRowHeight() throws IOException {
-        Workbook workbook = _testDataProvider.createWorkbook();
-        Sheet sheet = workbook.createSheet();
-        sheet.setDefaultRowHeightInPoints(15);
-        assertEquals((short) 300, sheet.getDefaultRowHeight());
-        assertEquals(15.0F, sheet.getDefaultRowHeightInPoints(), 0F);
-
-        Row row = sheet.createRow(1);
-        // new row inherits  default height from the sheet
-        assertEquals(sheet.getDefaultRowHeight(), row.getHeight());
-
-        // Set a new default row height in twips and test getting the value in points
-        sheet.setDefaultRowHeight((short) 360);
-        assertEquals(18.0f, sheet.getDefaultRowHeightInPoints(), 0F);
-        assertEquals((short) 360, sheet.getDefaultRowHeight());
-
-        // Test that defaultRowHeight is a truncated short: E.G. 360inPoints -> 18; 361inPoints -> 18
-        sheet.setDefaultRowHeight((short) 361);
-        assertEquals((float)361/20, sheet.getDefaultRowHeightInPoints(), 0F);
-        assertEquals((short) 361, sheet.getDefaultRowHeight());
-
-        // Set a new default row height in points and test getting the value in twips
-        sheet.setDefaultRowHeightInPoints(17.5f);
-        assertEquals(17.5f, sheet.getDefaultRowHeightInPoints(), 0F);
-        assertEquals((short)(17.5f*20), sheet.getDefaultRowHeight());
-        
-        workbook.close();
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            Sheet sheet = workbook.createSheet();
+            sheet.setDefaultRowHeightInPoints(15);
+            assertEquals((short) 300, sheet.getDefaultRowHeight());
+            assertEquals(15.0F, sheet.getDefaultRowHeightInPoints(), 0F);
+
+            Row row = sheet.createRow(1);
+            // new row inherits  default height from the sheet
+            assertEquals(sheet.getDefaultRowHeight(), row.getHeight());
+
+            // Set a new default row height in twips and test getting the value in points
+            sheet.setDefaultRowHeight((short) 360);
+            assertEquals(18.0f, sheet.getDefaultRowHeightInPoints(), 0F);
+            assertEquals((short) 360, sheet.getDefaultRowHeight());
+
+            // Test that defaultRowHeight is a truncated short: E.G. 360inPoints -> 18; 361inPoints -> 18
+            sheet.setDefaultRowHeight((short) 361);
+            assertEquals((float) 361 / 20, sheet.getDefaultRowHeightInPoints(), 0F);
+            assertEquals((short) 361, sheet.getDefaultRowHeight());
+
+            // Set a new default row height in points and test getting the value in twips
+            sheet.setDefaultRowHeightInPoints(17.5f);
+            assertEquals(17.5f, sheet.getDefaultRowHeightInPoints(), 0F);
+            assertEquals((short) (17.5f * 20), sheet.getDefaultRowHeight());
+        }
     }
 
     /** cell with formula becomes null on cloning a sheet*/
     @Test
     public void bug35084() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet s = wb.createSheet("Sheet1");
-        Row r = s.createRow(0);
-        r.createCell(0).setCellValue(1);
-        r.createCell(1).setCellFormula("A1*2");
-        Sheet s1 = wb.cloneSheet(0);
-        r = s1.getRow(0);
-        assertEquals("double", r.getCell(0).getNumericCellValue(), 1, 0); // sanity check
-        assertNotNull(r.getCell(1));
-        assertEquals("formula", r.getCell(1).getCellFormula(), "A1*2");
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet s = wb.createSheet("Sheet1");
+            Row r = s.createRow(0);
+            r.createCell(0).setCellValue(1);
+            r.createCell(1).setCellFormula("A1*2");
+            Sheet s1 = wb.cloneSheet(0);
+            r = s1.getRow(0);
+            assertEquals("double", r.getCell(0).getNumericCellValue(), 1, 0); // sanity check
+            assertNotNull(r.getCell(1));
+            assertEquals("formula", r.getCell(1).getCellFormula(), "A1*2");
+        }
     }
 
     /** test that new default column styles get applied */
     @Test
     public void defaultColumnStyle() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        CellStyle style = wb.createCellStyle();
-        Sheet sheet = wb.createSheet();
-        sheet.setDefaultColumnStyle(0, style);
-        assertNotNull(sheet.getColumnStyle(0));
-        assertEquals(style.getIndex(), sheet.getColumnStyle(0).getIndex());
-
-        Row row = sheet.createRow(0);
-        Cell cell = row.createCell(0);
-        CellStyle style2 = cell.getCellStyle();
-        assertNotNull(style2);
-        assertEquals("style should match", style.getIndex(), style2.getIndex());
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            CellStyle style = wb.createCellStyle();
+            Sheet sheet = wb.createSheet();
+            sheet.setDefaultColumnStyle(0, style);
+            assertNotNull(sheet.getColumnStyle(0));
+            assertEquals(style.getIndex(), sheet.getColumnStyle(0).getIndex());
+
+            Row row = sheet.createRow(0);
+            Cell cell = row.createCell(0);
+            CellStyle style2 = cell.getCellStyle();
+            assertNotNull(style2);
+            assertEquals("style should match", style.getIndex(), style2.getIndex());
+        }
     }
 
     @Test
     public void outlineProperties() throws IOException {
-        Workbook wb1 = _testDataProvider.createWorkbook();
-
-        Sheet sheet = wb1.createSheet();
+        try (Workbook wb1 = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb1.createSheet();
 
-        //TODO defaults are different in HSSF and XSSF
-        //assertTrue(sheet.getRowSumsBelow());
-        //assertTrue(sheet.getRowSumsRight());
+            //TODO defaults are different in HSSF and XSSF
+            //assertTrue(sheet.getRowSumsBelow());
+            //assertTrue(sheet.getRowSumsRight());
 
-        sheet.setRowSumsBelow(false);
-        sheet.setRowSumsRight(false);
+            sheet.setRowSumsBelow(false);
+            sheet.setRowSumsRight(false);
 
-        assertFalse(sheet.getRowSumsBelow());
-        assertFalse(sheet.getRowSumsRight());
+            assertFalse(sheet.getRowSumsBelow());
+            assertFalse(sheet.getRowSumsRight());
 
-        sheet.setRowSumsBelow(true);
-        sheet.setRowSumsRight(true);
+            sheet.setRowSumsBelow(true);
+            sheet.setRowSumsRight(true);
 
-        assertTrue(sheet.getRowSumsBelow());
-        assertTrue(sheet.getRowSumsRight());
+            assertTrue(sheet.getRowSumsBelow());
+            assertTrue(sheet.getRowSumsRight());
 
-        Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
-        wb1.close();
-        sheet = wb2.getSheetAt(0);
-        assertTrue(sheet.getRowSumsBelow());
-        assertTrue(sheet.getRowSumsRight());
-        wb2.close();
+            try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
+                sheet = wb2.getSheetAt(0);
+                assertTrue(sheet.getRowSumsBelow());
+                assertTrue(sheet.getRowSumsRight());
+            }
+        }
     }
 
     /**
@@ -719,61 +698,60 @@ public abstract class BaseTestSheet {
      */
     @Test
     public void sheetProperties() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet = wb.createSheet();
-
-        assertFalse(sheet.getHorizontallyCenter());
-        sheet.setHorizontallyCenter(true);
-        assertTrue(sheet.getHorizontallyCenter());
-        sheet.setHorizontallyCenter(false);
-        assertFalse(sheet.getHorizontallyCenter());
-
-        assertFalse(sheet.getVerticallyCenter());
-        sheet.setVerticallyCenter(true);
-        assertTrue(sheet.getVerticallyCenter());
-        sheet.setVerticallyCenter(false);
-        assertFalse(sheet.getVerticallyCenter());
-
-        assertFalse(sheet.isPrintGridlines());
-        sheet.setPrintGridlines(true);
-        assertTrue(sheet.isPrintGridlines());
-        
-        assertFalse(sheet.isPrintRowAndColumnHeadings());
-        sheet.setPrintRowAndColumnHeadings(true);
-        assertTrue(sheet.isPrintRowAndColumnHeadings());
-
-        assertFalse(sheet.isDisplayFormulas());
-        sheet.setDisplayFormulas(true);
-        assertTrue(sheet.isDisplayFormulas());
-
-        assertTrue(sheet.isDisplayGridlines());
-        sheet.setDisplayGridlines(false);
-        assertFalse(sheet.isDisplayGridlines());
-
-        //TODO: default "guts" is different in HSSF and XSSF
-        //assertTrue(sheet.getDisplayGuts());
-        sheet.setDisplayGuts(false);
-        assertFalse(sheet.getDisplayGuts());
-
-        assertTrue(sheet.isDisplayRowColHeadings());
-        sheet.setDisplayRowColHeadings(false);
-        assertFalse(sheet.isDisplayRowColHeadings());
-
-        //TODO: default "autobreaks" is different in HSSF and XSSF
-        //assertTrue(sheet.getAutobreaks());
-        sheet.setAutobreaks(false);
-        assertFalse(sheet.getAutobreaks());
-
-        assertFalse(sheet.getScenarioProtect());
-
-        //TODO: default "fit-to-page" is different in HSSF and XSSF
-        //assertFalse(sheet.getFitToPage());
-        sheet.setFitToPage(true);
-        assertTrue(sheet.getFitToPage());
-        sheet.setFitToPage(false);
-        assertFalse(sheet.getFitToPage());
-        
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb.createSheet();
+
+            assertFalse(sheet.getHorizontallyCenter());
+            sheet.setHorizontallyCenter(true);
+            assertTrue(sheet.getHorizontallyCenter());
+            sheet.setHorizontallyCenter(false);
+            assertFalse(sheet.getHorizontallyCenter());
+
+            assertFalse(sheet.getVerticallyCenter());
+            sheet.setVerticallyCenter(true);
+            assertTrue(sheet.getVerticallyCenter());
+            sheet.setVerticallyCenter(false);
+            assertFalse(sheet.getVerticallyCenter());
+
+            assertFalse(sheet.isPrintGridlines());
+            sheet.setPrintGridlines(true);
+            assertTrue(sheet.isPrintGridlines());
+
+            assertFalse(sheet.isPrintRowAndColumnHeadings());
+            sheet.setPrintRowAndColumnHeadings(true);
+            assertTrue(sheet.isPrintRowAndColumnHeadings());
+
+            assertFalse(sheet.isDisplayFormulas());
+            sheet.setDisplayFormulas(true);
+            assertTrue(sheet.isDisplayFormulas());
+
+            assertTrue(sheet.isDisplayGridlines());
+            sheet.setDisplayGridlines(false);
+            assertFalse(sheet.isDisplayGridlines());
+
+            //TODO: default "guts" is different in HSSF and XSSF
+            //assertTrue(sheet.getDisplayGuts());
+            sheet.setDisplayGuts(false);
+            assertFalse(sheet.getDisplayGuts());
+
+            assertTrue(sheet.isDisplayRowColHeadings());
+            sheet.setDisplayRowColHeadings(false);
+            assertFalse(sheet.isDisplayRowColHeadings());
+
+            //TODO: default "autobreaks" is different in HSSF and XSSF
+            //assertTrue(sheet.getAutobreaks());
+            sheet.setAutobreaks(false);
+            assertFalse(sheet.getAutobreaks());
+
+            assertFalse(sheet.getScenarioProtect());
+
+            //TODO: default "fit-to-page" is different in HSSF and XSSF
+            //assertFalse(sheet.getFitToPage());
+            sheet.setFitToPage(true);
+            assertTrue(sheet.getFitToPage());
+            sheet.setFitToPage(false);
+            assertFalse(sheet.getFitToPage());
+        }
     }
 
     public void baseTestGetSetMargin(double[] defaultMargins) throws IOException {
@@ -784,255 +762,254 @@ public abstract class BaseTestSheet {
         //double marginHeader = defaultMargins[4];
         //double marginFooter = defaultMargins[5];
 
-        Workbook workbook = _testDataProvider.createWorkbook();
-        Sheet sheet = workbook.createSheet("Sheet 1");
-        assertEquals(marginLeft, sheet.getMargin(Sheet.LeftMargin), 0.0);
-        sheet.setMargin(Sheet.LeftMargin, 10.0);
-        //left margin is custom, all others are default
-        assertEquals(10.0, sheet.getMargin(Sheet.LeftMargin), 0.0);
-        assertEquals(marginRight, sheet.getMargin(Sheet.RightMargin), 0.0);
-        assertEquals(marginTop, sheet.getMargin(Sheet.TopMargin), 0.0);
-        assertEquals(marginBottom, sheet.getMargin(Sheet.BottomMargin), 0.0);
-        sheet.setMargin(Sheet.RightMargin, 11.0);
-        assertEquals(11.0, sheet.getMargin(Sheet.RightMargin), 0.0);
-        sheet.setMargin(Sheet.TopMargin, 12.0);
-        assertEquals(12.0, sheet.getMargin(Sheet.TopMargin), 0.0);
-        sheet.setMargin(Sheet.BottomMargin, 13.0);
-        assertEquals(13.0, sheet.getMargin(Sheet.BottomMargin), 0.0);
-
-        sheet.setMargin(Sheet.FooterMargin, 5.6);
-        assertEquals(5.6, sheet.getMargin(Sheet.FooterMargin), 0.0);
-        sheet.setMargin(Sheet.HeaderMargin, 11.5);
-        assertEquals(11.5, sheet.getMargin(Sheet.HeaderMargin), 0.0);
-
-        // incorrect margin constant
-        thrown.expect(IllegalArgumentException.class);
-        thrown.expectMessage("Unknown margin constant:  65");
-        sheet.setMargin((short) 65, 15);
-        
-        workbook.close();
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            Sheet sheet = workbook.createSheet("Sheet 1");
+            assertEquals(marginLeft, sheet.getMargin(Sheet.LeftMargin), 0.0);
+            sheet.setMargin(Sheet.LeftMargin, 10.0);
+            //left margin is custom, all others are default
+            assertEquals(10.0, sheet.getMargin(Sheet.LeftMargin), 0.0);
+            assertEquals(marginRight, sheet.getMargin(Sheet.RightMargin), 0.0);
+            assertEquals(marginTop, sheet.getMargin(Sheet.TopMargin), 0.0);
+            assertEquals(marginBottom, sheet.getMargin(Sheet.BottomMargin), 0.0);
+            sheet.setMargin(Sheet.RightMargin, 11.0);
+            assertEquals(11.0, sheet.getMargin(Sheet.RightMargin), 0.0);
+            sheet.setMargin(Sheet.TopMargin, 12.0);
+            assertEquals(12.0, sheet.getMargin(Sheet.TopMargin), 0.0);
+            sheet.setMargin(Sheet.BottomMargin, 13.0);
+            assertEquals(13.0, sheet.getMargin(Sheet.BottomMargin), 0.0);
+
+            sheet.setMargin(Sheet.FooterMargin, 5.6);
+            assertEquals(5.6, sheet.getMargin(Sheet.FooterMargin), 0.0);
+            sheet.setMargin(Sheet.HeaderMargin, 11.5);
+            assertEquals(11.5, sheet.getMargin(Sheet.HeaderMargin), 0.0);
+
+            // incorrect margin constant
+            IllegalArgumentException ex = assertThrows(
+                IllegalArgumentException.class,
+                () -> sheet.setMargin((short) 65, 15)
+            );
+            assertEquals("Unknown margin constant:  65", ex.getMessage());
+        }
     }
 
     @Test
     public void rowBreaks() throws IOException {
-        Workbook workbook = _testDataProvider.createWorkbook();
-        Sheet sheet = workbook.createSheet();
-        //Sheet#getRowBreaks() returns an empty array if no row breaks are defined
-        assertNotNull(sheet.getRowBreaks());
-        assertEquals(0, sheet.getRowBreaks().length);
-
-        sheet.setRowBreak(1);
-        assertEquals(1, sheet.getRowBreaks().length);
-        sheet.setRowBreak(15);
-        assertEquals(2, sheet.getRowBreaks().length);
-        assertEquals(1, sheet.getRowBreaks()[0]);
-        assertEquals(15, sheet.getRowBreaks()[1]);
-        sheet.setRowBreak(1);
-        assertEquals(2, sheet.getRowBreaks().length);
-        assertTrue(sheet.isRowBroken(1));
-        assertTrue(sheet.isRowBroken(15));
-
-        //now remove the created breaks
-        sheet.removeRowBreak(1);
-        assertEquals(1, sheet.getRowBreaks().length);
-        sheet.removeRowBreak(15);
-        assertEquals(0, sheet.getRowBreaks().length);
-
-        assertFalse(sheet.isRowBroken(1));
-        assertFalse(sheet.isRowBroken(15));
-        
-        workbook.close();
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            Sheet sheet = workbook.createSheet();
+            //Sheet#getRowBreaks() returns an empty array if no row breaks are defined
+            assertNotNull(sheet.getRowBreaks());
+            assertEquals(0, sheet.getRowBreaks().length);
+
+            sheet.setRowBreak(1);
+            assertEquals(1, sheet.getRowBreaks().length);
+            sheet.setRowBreak(15);
+            assertEquals(2, sheet.getRowBreaks().length);
+            assertEquals(1, sheet.getRowBreaks()[0]);
+            assertEquals(15, sheet.getRowBreaks()[1]);
+            sheet.setRowBreak(1);
+            assertEquals(2, sheet.getRowBreaks().length);
+            assertTrue(sheet.isRowBroken(1));
+            assertTrue(sheet.isRowBroken(15));
+
+            //now remove the created breaks
+            sheet.removeRowBreak(1);
+            assertEquals(1, sheet.getRowBreaks().length);
+            sheet.removeRowBreak(15);
+            assertEquals(0, sheet.getRowBreaks().length);
+
+            assertFalse(sheet.isRowBroken(1));
+            assertFalse(sheet.isRowBroken(15));
+        }
     }
 
     @Test
     public void columnBreaks() throws IOException {
-        Workbook workbook = _testDataProvider.createWorkbook();
-        Sheet sheet = workbook.createSheet();
-        assertNotNull(sheet.getColumnBreaks());
-        assertEquals(0, sheet.getColumnBreaks().length);
-
-        assertFalse(sheet.isColumnBroken(0));
-
-        sheet.setColumnBreak(11);
-        assertNotNull(sheet.getColumnBreaks());
-        assertEquals(11, sheet.getColumnBreaks()[0]);
-        sheet.setColumnBreak(12);
-        assertEquals(2, sheet.getColumnBreaks().length);
-        assertTrue(sheet.isColumnBroken(11));
-        assertTrue(sheet.isColumnBroken(12));
-
-        sheet.removeColumnBreak((short) 11);
-        assertEquals(1, sheet.getColumnBreaks().length);
-        sheet.removeColumnBreak((short) 15); //remove non-existing
-        assertEquals(1, sheet.getColumnBreaks().length);
-        sheet.removeColumnBreak((short) 12);
-        assertEquals(0, sheet.getColumnBreaks().length);
-
-        assertFalse(sheet.isColumnBroken(11));
-        assertFalse(sheet.isColumnBroken(12));
-        workbook.close();
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            Sheet sheet = workbook.createSheet();
+            assertNotNull(sheet.getColumnBreaks());
+            assertEquals(0, sheet.getColumnBreaks().length);
+
+            assertFalse(sheet.isColumnBroken(0));
+
+            sheet.setColumnBreak(11);
+            assertNotNull(sheet.getColumnBreaks());
+            assertEquals(11, sheet.getColumnBreaks()[0]);
+            sheet.setColumnBreak(12);
+            assertEquals(2, sheet.getColumnBreaks().length);
+            assertTrue(sheet.isColumnBroken(11));
+            assertTrue(sheet.isColumnBroken(12));
+
+            sheet.removeColumnBreak((short) 11);
+            assertEquals(1, sheet.getColumnBreaks().length);
+            sheet.removeColumnBreak((short) 15); //remove non-existing
+            assertEquals(1, sheet.getColumnBreaks().length);
+            sheet.removeColumnBreak((short) 12);
+            assertEquals(0, sheet.getColumnBreaks().length);
+
+            assertFalse(sheet.isColumnBroken(11));
+            assertFalse(sheet.isColumnBroken(12));
+        }
     }
 
     @Test
     public void getFirstLastRowNum() throws IOException {
-        Workbook workbook = _testDataProvider.createWorkbook();
-        Sheet sheet = workbook.createSheet("Sheet 1");
-        sheet.createRow(9);
-        sheet.createRow(0);
-        sheet.createRow(1);
-        assertEquals(0, sheet.getFirstRowNum());
-        assertEquals(9, sheet.getLastRowNum());
-        workbook.close();
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            Sheet sheet = workbook.createSheet("Sheet 1");
+            sheet.createRow(9);
+            sheet.createRow(0);
+            sheet.createRow(1);
+            assertEquals(0, sheet.getFirstRowNum());
+            assertEquals(9, sheet.getLastRowNum());
+        }
     }
 
     @Test
     public void getFooter() throws IOException {
-        Workbook workbook = _testDataProvider.createWorkbook();
-        Sheet sheet = workbook.createSheet("Sheet 1");
-        assertNotNull(sheet.getFooter());
-        sheet.getFooter().setCenter("test center footer");
-        assertEquals("test center footer", sheet.getFooter().getCenter());
-        workbook.close();
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            Sheet sheet = workbook.createSheet("Sheet 1");
+            assertNotNull(sheet.getFooter());
+            sheet.getFooter().setCenter("test center footer");
+            assertEquals("test center footer", sheet.getFooter().getCenter());
+        }
     }
 
     @Test
     public void getSetColumnHidden() throws IOException {
-        Workbook workbook = _testDataProvider.createWorkbook();
-        Sheet sheet = workbook.createSheet("Sheet 1");
-        sheet.setColumnHidden(2, true);
-        assertTrue(sheet.isColumnHidden(2));
-        workbook.close();
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            Sheet sheet = workbook.createSheet("Sheet 1");
+            sheet.setColumnHidden(2, true);
+            assertTrue(sheet.isColumnHidden(2));
+        }
     }
 
     @Test
     public void protectSheet() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet = wb.createSheet();
-        assertFalse(sheet.getProtect());
-        sheet.protectSheet("Test");  
-        assertTrue(sheet.getProtect());
-        sheet.protectSheet(null);
-        assertFalse(sheet.getProtect());
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb.createSheet();
+            assertFalse(sheet.getProtect());
+            sheet.protectSheet("Test");
+            assertTrue(sheet.getProtect());
+            sheet.protectSheet(null);
+            assertFalse(sheet.getProtect());
+        }
     }
 
     @Test
     public void createFreezePane() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        // create a workbook
-        Sheet sheet = wb.createSheet();
-        assertNull(sheet.getPaneInformation());
-        sheet.createFreezePane(0, 0);
-        // still null
-        assertNull(sheet.getPaneInformation());
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            // create a workbook
+            Sheet sheet = wb.createSheet();
+            assertNull(sheet.getPaneInformation());
+            sheet.createFreezePane(0, 0);
+            // still null
+            assertNull(sheet.getPaneInformation());
 
-        sheet.createFreezePane(2, 3);
+            sheet.createFreezePane(2, 3);
 
-        PaneInformation info = sheet.getPaneInformation();
+            PaneInformation info = sheet.getPaneInformation();
 
 
-        assertEquals(PaneInformation.PANE_LOWER_RIGHT, info.getActivePane());
-        assertEquals(3, info.getHorizontalSplitPosition());
-        assertEquals(3, info.getHorizontalSplitTopRow());
-        assertEquals(2, info.getVerticalSplitLeftColumn());
-        assertEquals(2, info.getVerticalSplitPosition());
+            assertEquals(PaneInformation.PANE_LOWER_RIGHT, info.getActivePane());
+            assertEquals(3, info.getHorizontalSplitPosition());
+            assertEquals(3, info.getHorizontalSplitTopRow());
+            assertEquals(2, info.getVerticalSplitLeftColumn());
+            assertEquals(2, info.getVerticalSplitPosition());
 
-        sheet.createFreezePane(0, 0);
-        // If both colSplit and rowSplit are zero then the existing freeze pane is removed
-        assertNull(sheet.getPaneInformation());
+            sheet.createFreezePane(0, 0);
+            // If both colSplit and rowSplit are zero then the existing freeze pane is removed
+            assertNull(sheet.getPaneInformation());
 
-        sheet.createFreezePane(0, 3);
+            sheet.createFreezePane(0, 3);
 
-        info = sheet.getPaneInformation();
+            info = sheet.getPaneInformation();
 
-        assertEquals(PaneInformation.PANE_LOWER_LEFT, info.getActivePane());
-        assertEquals(3, info.getHorizontalSplitPosition());
-        assertEquals(3, info.getHorizontalSplitTopRow());
-        assertEquals(0, info.getVerticalSplitLeftColumn());
-        assertEquals(0, info.getVerticalSplitPosition());
+            assertEquals(PaneInformation.PANE_LOWER_LEFT, info.getActivePane());
+            assertEquals(3, info.getHorizontalSplitPosition());
+            assertEquals(3, info.getHorizontalSplitTopRow());
+            assertEquals(0, info.getVerticalSplitLeftColumn());
+            assertEquals(0, info.getVerticalSplitPosition());
 
-        sheet.createFreezePane(3, 0);
+            sheet.createFreezePane(3, 0);
 
-        info = sheet.getPaneInformation();
+            info = sheet.getPaneInformation();
 
-        assertEquals(PaneInformation.PANE_UPPER_RIGHT, info.getActivePane());
-        assertEquals(0, info.getHorizontalSplitPosition());
-        assertEquals(0, info.getHorizontalSplitTopRow());
-        assertEquals(3, info.getVerticalSplitLeftColumn());
-        assertEquals(3, info.getVerticalSplitPosition());
+            assertEquals(PaneInformation.PANE_UPPER_RIGHT, info.getActivePane());
+            assertEquals(0, info.getHorizontalSplitPosition());
+            assertEquals(0, info.getHorizontalSplitTopRow());
+            assertEquals(3, info.getVerticalSplitLeftColumn());
+            assertEquals(3, info.getVerticalSplitPosition());
 
-        sheet.createFreezePane(0, 0);
-        // If both colSplit and rowSplit are zero then the existing freeze pane is removed
-        assertNull(sheet.getPaneInformation());
-        
-        wb.close();
+            sheet.createFreezePane(0, 0);
+            // If both colSplit and rowSplit are zero then the existing freeze pane is removed
+            assertNull(sheet.getPaneInformation());
+        }
     }
 
-    
+
     @Test
     public void getRepeatingRowsAndColumns() throws IOException {
-        Workbook wb = _testDataProvider.openSampleWorkbook(
-            "RepeatingRowsCols." 
-            + _testDataProvider.getStandardFileNameExtension());
-        
-        checkRepeatingRowsAndColumns(wb.getSheetAt(0), null, null);
-        checkRepeatingRowsAndColumns(wb.getSheetAt(1), "1:1", null);
-        checkRepeatingRowsAndColumns(wb.getSheetAt(2), null, "A:A");
-        checkRepeatingRowsAndColumns(wb.getSheetAt(3), "2:3", "A:B");
-        wb.close();
+        try (Workbook wb = _testDataProvider.openSampleWorkbook(
+            "RepeatingRowsCols."
+            + _testDataProvider.getStandardFileNameExtension())) {
+
+            checkRepeatingRowsAndColumns(wb.getSheetAt(0), null, null);
+            checkRepeatingRowsAndColumns(wb.getSheetAt(1), "1:1", null);
+            checkRepeatingRowsAndColumns(wb.getSheetAt(2), null, "A:A");
+            checkRepeatingRowsAndColumns(wb.getSheetAt(3), "2:3", "A:B");
+        }
     }
 
 
     @Test
     public void setRepeatingRowsAndColumnsBug47294() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet1 = wb.createSheet();
-        sheet1.setRepeatingRows(CellRangeAddress.valueOf("1:4"));
-        assertEquals("1:4", sheet1.getRepeatingRows().formatAsString());
-
-        //must handle sheets with quotas, see Bugzilla #47294
-        Sheet sheet2 = wb.createSheet("My' Sheet");
-        sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:4"));
-        assertEquals("1:4", sheet2.getRepeatingRows().formatAsString());
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet1 = wb.createSheet();
+            sheet1.setRepeatingRows(CellRangeAddress.valueOf("1:4"));
+            assertEquals("1:4", sheet1.getRepeatingRows().formatAsString());
+
+            //must handle sheets with quotas, see Bugzilla #47294
+            Sheet sheet2 = wb.createSheet("My' Sheet");
+            sheet2.setRepeatingRows(CellRangeAddress.valueOf("1:4"));
+            assertEquals("1:4", sheet2.getRepeatingRows().formatAsString());
+        }
     }
 
     @Test
     public void setRepeatingRowsAndColumns() throws IOException {
-        Workbook wb1 = _testDataProvider.createWorkbook();
-        Sheet sheet1 = wb1.createSheet("Sheet1");
-        Sheet sheet2 = wb1.createSheet("Sheet2");
-        Sheet sheet3 = wb1.createSheet("Sheet3");
-        
-        checkRepeatingRowsAndColumns(sheet1, null, null);
-        
-        sheet1.setRepeatingRows(CellRangeAddress.valueOf("4:5"));
-        sheet2.setRepeatingColumns(CellRangeAddress.valueOf("A:C"));
-        sheet3.setRepeatingRows(CellRangeAddress.valueOf("1:4"));
-        sheet3.setRepeatingColumns(CellRangeAddress.valueOf("A:A"));
-        
-        checkRepeatingRowsAndColumns(sheet1, "4:5", null);
-        checkRepeatingRowsAndColumns(sheet2, null, "A:C");
-        checkRepeatingRowsAndColumns(sheet3, "1:4", "A:A");
-        
-        // write out, read back, and test refrain...
-        Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
-        wb1.close();
-        sheet1 = wb2.getSheetAt(0);
-        sheet2 = wb2.getSheetAt(1);
-        sheet3 = wb2.getSheetAt(2);
-        
-        checkRepeatingRowsAndColumns(sheet1, "4:5", null);
-        checkRepeatingRowsAndColumns(sheet2, null, "A:C");
-        checkRepeatingRowsAndColumns(sheet3, "1:4", "A:A");
-        
-        // check removing repeating rows and columns       
-        sheet3.setRepeatingRows(null);
-        checkRepeatingRowsAndColumns(sheet3, null, "A:A");
-        
-        sheet3.setRepeatingColumns(null);
-        checkRepeatingRowsAndColumns(sheet3, null, null);
-        wb2.close();
+        try (Workbook wb1 = _testDataProvider.createWorkbook()) {
+            Sheet sheet1 = wb1.createSheet("Sheet1");
+            Sheet sheet2 = wb1.createSheet("Sheet2");
+            Sheet sheet3 = wb1.createSheet("Sheet3");
+
+            checkRepeatingRowsAndColumns(sheet1, null, null);
+
+            sheet1.setRepeatingRows(CellRangeAddress.valueOf("4:5"));
+            sheet2.setRepeatingColumns(CellRangeAddress.valueOf("A:C"));
+            sheet3.setRepeatingRows(CellRangeAddress.valueOf("1:4"));
+            sheet3.setRepeatingColumns(CellRangeAddress.valueOf("A:A"));
+
+            checkRepeatingRowsAndColumns(sheet1, "4:5", null);
+            checkRepeatingRowsAndColumns(sheet2, null, "A:C");
+            checkRepeatingRowsAndColumns(sheet3, "1:4", "A:A");
+
+            // write out, read back, and test refrain...
+            try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
+                sheet1 = wb2.getSheetAt(0);
+                sheet2 = wb2.getSheetAt(1);
+                sheet3 = wb2.getSheetAt(2);
+
+                checkRepeatingRowsAndColumns(sheet1, "4:5", null);
+                checkRepeatingRowsAndColumns(sheet2, null, "A:C");
+                checkRepeatingRowsAndColumns(sheet3, "1:4", "A:A");
+
+                // check removing repeating rows and columns
+                sheet3.setRepeatingRows(null);
+                checkRepeatingRowsAndColumns(sheet3, null, "A:A");
+
+                sheet3.setRepeatingColumns(null);
+                checkRepeatingRowsAndColumns(sheet3, null, null);
+            }
+        }
     }
 
     private void checkRepeatingRowsAndColumns(
@@ -1051,61 +1028,60 @@ public abstract class BaseTestSheet {
 
     @Test
     public void baseZoom() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet = wb.createSheet();
-        
-        // here we can only verify that setting some zoom values works, range-checking is different between the implementations
-        sheet.setZoom(75);
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb.createSheet();
+
+            // here we can only verify that setting some zoom values works,
+            // range-checking is different between the implementations
+            sheet.setZoom(75);
+        }
     }
-    
+
     @Test
     public void baseShowInPane() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet = wb.createSheet();
-        sheet.showInPane(2, 3);
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb.createSheet();
+            sheet.showInPane(2, 3);
+        }
     }
 
     @Test
     public void bug55723() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet = wb.createSheet();
-
-        CellRangeAddress range = CellRangeAddress.valueOf("A:B");
-        AutoFilter filter = sheet.setAutoFilter(range);
-        assertNotNull(filter);
-        // there seems to be currently no generic way to check the setting...
-
-        range = CellRangeAddress.valueOf("B:C");
-        filter = sheet.setAutoFilter(range);
-        assertNotNull(filter);
-        // there seems to be currently no generic way to check the setting...
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb.createSheet();
+
+            CellRangeAddress range = CellRangeAddress.valueOf("A:B");
+            AutoFilter filter = sheet.setAutoFilter(range);
+            assertNotNull(filter);
+            // there seems to be currently no generic way to check the setting...
+
+            range = CellRangeAddress.valueOf("B:C");
+            filter = sheet.setAutoFilter(range);
+            assertNotNull(filter);
+            // there seems to be currently no generic way to check the setting...
+        }
     }
 
     @Test
     public void bug55723_Rows() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet = wb.createSheet();
-
-        CellRangeAddress range = CellRangeAddress.valueOf("A4:B55000");
-        AutoFilter filter = sheet.setAutoFilter(range);
-        assertNotNull(filter);
-        
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb.createSheet();
+
+            CellRangeAddress range = CellRangeAddress.valueOf("A4:B55000");
+            AutoFilter filter = sheet.setAutoFilter(range);
+            assertNotNull(filter);
+        }
     }
 
     @Test
     public void bug55723d_RowsOver65k() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet = wb.createSheet();
-
-        CellRangeAddress range = CellRangeAddress.valueOf("A4:B75000");
-        AutoFilter filter = sheet.setAutoFilter(range);
-        assertNotNull(filter);
-        
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb.createSheet();
+
+            CellRangeAddress range = CellRangeAddress.valueOf("A4:B75000");
+            AutoFilter filter = sheet.setAutoFilter(range);
+            assertNotNull(filter);
+        }
     }
 
     /**
@@ -1113,179 +1089,177 @@ public abstract class BaseTestSheet {
      */
     @Test
     public void bug48325() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet = wb.createSheet("Test");
-        trackColumnsForAutoSizingIfSXSSF(sheet);
-        CreationHelper factory = wb.getCreationHelper();
-
-        Row row = sheet.createRow(0);
-        Cell cell = row.createCell(0);
-
-        Font font = wb.createFont();
-        RichTextString rts = factory.createRichTextString("");
-        rts.applyFont(font);
-        cell.setCellValue(rts);
-
-        sheet.autoSizeColumn(0);
-        
-        assertNotNull(_testDataProvider.writeOutAndReadBack(wb));
-        
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb.createSheet("Test");
+            trackColumnsForAutoSizingIfSXSSF(sheet);
+            CreationHelper factory = wb.getCreationHelper();
+
+            Row row = sheet.createRow(0);
+            Cell cell = row.createCell(0);
+
+            Font font = wb.createFont();
+            RichTextString rts = factory.createRichTextString("");
+            rts.applyFont(font);
+            cell.setCellValue(rts);
+
+            sheet.autoSizeColumn(0);
+
+            assertNotNull(_testDataProvider.writeOutAndReadBack(wb));
+        }
     }
 
     @Test
     public void getCellComment() throws IOException {
-        Workbook workbook = _testDataProvider.createWorkbook();
-        Sheet sheet = workbook.createSheet();
-        Drawing<?> dg = sheet.createDrawingPatriarch();
-        Comment comment = dg.createCellComment(workbook.getCreationHelper().createClientAnchor());
-        Cell cell = sheet.createRow(9).createCell(2);
-        comment.setAuthor("test C10 author");
-        cell.setCellComment(comment);
-
-        CellAddress ref = new CellAddress(9, 2);
-        assertNotNull(sheet.getCellComment(ref));
-        assertEquals("test C10 author", sheet.getCellComment(ref).getAuthor());
-        
-        assertNotNull(_testDataProvider.writeOutAndReadBack(workbook));
-        
-        workbook.close();
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            Sheet sheet = workbook.createSheet();
+            Drawing<?> dg = sheet.createDrawingPatriarch();
+            Comment comment = dg.createCellComment(workbook.getCreationHelper().createClientAnchor());
+            Cell cell = sheet.createRow(9).createCell(2);
+            comment.setAuthor("test C10 author");
+            cell.setCellComment(comment);
+
+            CellAddress ref = new CellAddress(9, 2);
+            assertNotNull(sheet.getCellComment(ref));
+            assertEquals("test C10 author", sheet.getCellComment(ref).getAuthor());
+
+            assertNotNull(_testDataProvider.writeOutAndReadBack(workbook));
+        }
     }
 
     @Test
     public void getCellComments() throws IOException {
-        Workbook workbook = _testDataProvider.createWorkbook();
-        Sheet sheet = workbook.createSheet("TEST");
-
-        // a sheet with no cell comments should return an empty map (not null or raise NPE).
-        assertTrue(sheet.getCellComments().isEmpty());
-
-        Drawing<?> dg = sheet.createDrawingPatriarch();
-        ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor();
-        
-        int nRows = 5;
-        int nCols = 6;
-        
-        for (int r=0; r<nRows; r++) {
-            sheet.createRow(r);
-            // Create columns in reverse order
-            for (int c=nCols-1; c>=0; c--) {
-                // When the comment box is visible, have it show in a 1x3 space
-                anchor.setCol1(c);
-                anchor.setCol2(c);
-                anchor.setRow1(r);
-                anchor.setRow2(r);
-                
-                // Create the comment and set the text-author
-                Comment comment = dg.createCellComment(anchor);
-                Cell cell = sheet.getRow(r).createCell(c);
-                comment.setAuthor("Author " + r);
-                RichTextString text = workbook.getCreationHelper().createRichTextString("Test comment at row=" + r + ", column=" + c);
-                comment.setString(text);
-                
-                // Assign the comment to the cell
-                cell.setCellComment(comment);
+        try (Workbook wb1 = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb1.createSheet("TEST");
+
+            // a sheet with no cell comments should return an empty map (not null or raise NPE).
+            assertTrue(sheet.getCellComments().isEmpty());
+
+            Drawing<?> dg = sheet.createDrawingPatriarch();
+            ClientAnchor anchor = wb1.getCreationHelper().createClientAnchor();
+
+            int nRows = 5;
+            int nCols = 6;
+
+            for (int r = 0; r < nRows; r++) {
+                sheet.createRow(r);
+                // Create columns in reverse order
+                for (int c = nCols - 1; c >= 0; c--) {
+                    // When the comment box is visible, have it show in a 1x3 space
+                    anchor.setCol1(c);
+                    anchor.setCol2(c);
+                    anchor.setRow1(r);
+                    anchor.setRow2(r);
+
+                    // Create the comment and set the text-author
+                    Comment comment = dg.createCellComment(anchor);
+                    Cell cell = sheet.getRow(r).createCell(c);
+                    comment.setAuthor("Author " + r);
+                    RichTextString text = wb1.getCreationHelper().createRichTextString("Test comment at row=" + r + ", column=" + c);
+                    comment.setString(text);
+
+                    // Assign the comment to the cell
+                    cell.setCellComment(comment);
+                }
+            }
+
+            try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
+                Sheet sh = wb2.getSheet("TEST");
+                Map<CellAddress, ? extends Comment> cellComments = sh.getCellComments();
+                assertEquals(nRows * nCols, cellComments.size());
+
+                for (Entry<CellAddress, ? extends Comment> e : cellComments.entrySet()) {
+                    CellAddress ref = e.getKey();
+                    Comment aComment = e.getValue();
+                    assertEquals("Author " + ref.getRow(), aComment.getAuthor());
+                    String text = "Test comment at row=" + ref.getRow() + ", column=" + ref.getColumn();
+                    assertEquals(text, aComment.getString().getString());
+                }
             }
         }
-        
-        Workbook wb = _testDataProvider.writeOutAndReadBack(workbook);
-        Sheet sh = wb.getSheet("TEST");
-        Map<CellAddress, ? extends Comment> cellComments = sh.getCellComments();
-        assertEquals(nRows*nCols, cellComments.size());
-        
-        for (Entry<CellAddress, ? extends Comment> e : cellComments.entrySet()) {
-            CellAddress ref = e.getKey();
-            Comment aComment = e.getValue();
-            assertEquals("Author " + ref.getRow(), aComment.getAuthor());
-            String text = "Test comment at row=" + ref.getRow() + ", column=" + ref.getColumn();
-            assertEquals(text, aComment.getString().getString());
-        }
-        
-        workbook.close();
-        wb.close();
     }
-    
+
     @Test
     public void getHyperlink() throws IOException {
-        Workbook workbook = _testDataProvider.createWorkbook();
-        Hyperlink hyperlink = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL);
-        hyperlink.setAddress("https://poi.apache.org/");
-        
-        Sheet sheet = workbook.createSheet();
-        Cell cell = sheet.createRow(5).createCell(1);
-        
-        assertEquals("list size before add", 0, sheet.getHyperlinkList().size());
-        cell.setHyperlink(hyperlink);
-        assertEquals("list size after add", 1, sheet.getHyperlinkList().size());
-        
-        assertEquals("list", hyperlink, sheet.getHyperlinkList().get(0));
-        CellAddress B6 = new CellAddress(5, 1);
-        assertEquals("row, col", hyperlink, sheet.getHyperlink(5, 1));
-        assertEquals("addr", hyperlink, sheet.getHyperlink(B6));
-        assertNull("no hyperlink at A1", sheet.getHyperlink(CellAddress.A1));
-        
-        workbook.close();
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            Hyperlink hyperlink = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL);
+            hyperlink.setAddress("https://poi.apache.org/");
+
+            Sheet sheet = workbook.createSheet();
+            Cell cell = sheet.createRow(5).createCell(1);
+
+            assertEquals("list size before add", 0, sheet.getHyperlinkList().size());
+            cell.setHyperlink(hyperlink);
+            assertEquals("list size after add", 1, sheet.getHyperlinkList().size());
+
+            assertEquals("list", hyperlink, sheet.getHyperlinkList().get(0));
+            CellAddress B6 = new CellAddress(5, 1);
+            assertEquals("row, col", hyperlink, sheet.getHyperlink(5, 1));
+            assertEquals("addr", hyperlink, sheet.getHyperlink(B6));
+            assertNull("no hyperlink at A1", sheet.getHyperlink(CellAddress.A1));
+        }
     }
-    
+
     @Test
-    public void removeAllHyperlinks() {
-        Workbook workbook = _testDataProvider.createWorkbook();
-        Hyperlink hyperlink = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL);
-        hyperlink.setAddress("https://poi.apache.org/");
-        Sheet sheet = workbook.createSheet();
-        Cell cell = sheet.createRow(5).createCell(1);
-        cell.setHyperlink(hyperlink);
-        
-        assertEquals(1, workbook.getSheetAt(0).getHyperlinkList().size());
-        // Save a workbook with a hyperlink
-        Workbook workbook2 = _testDataProvider.writeOutAndReadBack(workbook);
-        assertEquals(1, workbook2.getSheetAt(0).getHyperlinkList().size());
-        
-        // Remove all hyperlinks from a saved workbook
-        workbook2.getSheetAt(0).getRow(5).getCell(1).removeHyperlink();
-        assertEquals(0, workbook2.getSheetAt(0).getHyperlinkList().size());
-        
-        // Verify that hyperlink was removed from workbook after writing out
-        Workbook workbook3 = _testDataProvider.writeOutAndReadBack(workbook2);
-        assertEquals(0, workbook3.getSheetAt(0).getHyperlinkList().size());
+    public void removeAllHyperlinks() throws IOException {
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            Hyperlink hyperlink = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL);
+            hyperlink.setAddress("https://poi.apache.org/");
+            Sheet sheet = workbook.createSheet();
+            Cell cell = sheet.createRow(5).createCell(1);
+            cell.setHyperlink(hyperlink);
+
+            assertEquals(1, workbook.getSheetAt(0).getHyperlinkList().size());
+
+            // Save a workbook with a hyperlink
+            try (Workbook workbook2 = _testDataProvider.writeOutAndReadBack(workbook)) {
+                assertEquals(1, workbook2.getSheetAt(0).getHyperlinkList().size());
+
+                // Remove all hyperlinks from a saved workbook
+                workbook2.getSheetAt(0).getRow(5).getCell(1).removeHyperlink();
+                assertEquals(0, workbook2.getSheetAt(0).getHyperlinkList().size());
+
+                // Verify that hyperlink was removed from workbook after writing out
+                try (Workbook workbook3 = _testDataProvider.writeOutAndReadBack(workbook2)) {
+                    assertEquals(0, workbook3.getSheetAt(0).getHyperlinkList().size());
+                }
+            }
+        }
     }
 
 
     @Test
     public void newMergedRegionAt() throws IOException {
-        Workbook workbook = _testDataProvider.createWorkbook();
-        Sheet sheet = workbook.createSheet();
-        CellRangeAddress region = CellRangeAddress.valueOf("B2:D4");
-        assertEquals(0, sheet.addMergedRegion(region));
-        assertEquals("B2:D4", sheet.getMergedRegion(0).formatAsString());
-        assertEquals(1, sheet.getNumMergedRegions());
-        
-        assertNotNull(_testDataProvider.writeOutAndReadBack(workbook));
-        
-        workbook.close();
+        try (Workbook workbook = _testDataProvider.createWorkbook()) {
+            Sheet sheet = workbook.createSheet();
+            CellRangeAddress region = CellRangeAddress.valueOf("B2:D4");
+            assertEquals(0, sheet.addMergedRegion(region));
+            assertEquals("B2:D4", sheet.getMergedRegion(0).formatAsString());
+            assertEquals(1, sheet.getNumMergedRegions());
+
+            assertNotNull(_testDataProvider.writeOutAndReadBack(workbook));
+        }
     }
 
     @Test
     public void showInPaneManyRowsBug55248() throws IOException {
-        Workbook wb1 = _testDataProvider.createWorkbook();
-        Sheet sheet = wb1.createSheet("Sheet 1");
+        try (Workbook wb1 = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb1.createSheet("Sheet 1");
 
-        sheet.showInPane(0, 0);
+            sheet.showInPane(0, 0);
 
-        for(int i = ROW_COUNT/2;i < ROW_COUNT;i++) {
-            sheet.createRow(i);
-            sheet.showInPane(i, 0);
-            // this one fails: sheet.showInPane((short)i, 0);
-        }
+            for (int i = ROW_COUNT / 2; i < ROW_COUNT; i++) {
+                sheet.createRow(i);
+                sheet.showInPane(i, 0);
+                // this one fails: sheet.showInPane((short)i, 0);
+            }
 
-        int i = 0;
-        sheet.showInPane(i, i);
+            int i = 0;
+            sheet.showInPane(i, i);
 
-        Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
-        checkRowCount(wb2);
-        
-        wb2.close();
-        wb1.close();
+            try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
+                checkRowCount(wb2);
+            }
+        }
     }
 
     private void checkRowCount(Workbook wb) {
@@ -1294,28 +1268,27 @@ public abstract class BaseTestSheet {
         assertNotNull(sh);
         assertEquals(ROW_COUNT-1, sh.getLastRowNum());
     }
-    
-    
+
+
     @Test
     public void testRightToLeft() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet = wb.createSheet();
-
-        assertFalse(sheet.isRightToLeft());
-        sheet.setRightToLeft(true);
-        assertTrue(sheet.isRightToLeft());
-        sheet.setRightToLeft(false);
-        assertFalse(sheet.isRightToLeft());
-        
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb.createSheet();
+
+            assertFalse(sheet.isRightToLeft());
+            sheet.setRightToLeft(true);
+            assertTrue(sheet.isRightToLeft());
+            sheet.setRightToLeft(false);
+            assertFalse(sheet.isRightToLeft());
+        }
     }
-    
+
     @Test
     public void testNoMergedRegionsIsEmptyList() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet = wb.createSheet();
-        assertTrue(sheet.getMergedRegions().isEmpty());
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb.createSheet();
+            assertTrue(sheet.getMergedRegions().isEmpty());
+        }
     }
 
     /**
@@ -1323,63 +1296,61 @@ public abstract class BaseTestSheet {
      */
     @Test
     public void setActiveCell() throws IOException {
-        Workbook wb1 = _testDataProvider.createWorkbook();
-        Sheet sheet = wb1.createSheet();
-        CellAddress B42 = new CellAddress("B42");
-        
-        // active cell behavior is undefined if not set.
-        // HSSFSheet defaults to A1 active cell, while XSSFSheet defaults to null.
-        if (sheet.getActiveCell() != null && !sheet.getActiveCell().equals(CellAddress.A1)) {
-            fail("If not set, active cell should default to null or A1");
-        }
-
-        sheet.setActiveCell(B42);
-
-        Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1);
+        try (Workbook wb1 = _testDataProvider.createWorkbook()) {
+            Sheet sheet = wb1.createSheet();
+            CellAddress B42 = new CellAddress("B42");
+
+            // active cell behavior is undefined if not set.
+            // HSSFSheet defaults to A1 active cell, while XSSFSheet defaults to null.
+            if (sheet.getActiveCell() != null && !sheet.getActiveCell().equals(CellAddress.A1)) {
+                fail("If not set, active cell should default to null or A1");
+            }
 
-        assertEquals(B42, sheet.getActiveCell());
+            sheet.setActiveCell(B42);
 
-        wb1.close();
-        wb2.close();
+            try (Workbook wb2 = _testDataProvider.writeOutAndReadBack(wb1)) {
+                sheet = wb2.getSheetAt(0);
+                assertEquals(B42, sheet.getActiveCell());
+            }
+        }
     }
 
 
     @Test
     public void autoSizeDate() throws IOException {
-        Workbook wb = _testDataProvider.createWorkbook();
-        Sheet s = wb.createSheet("Sheet1");
-        Row r = s.createRow(0);
-        r.createCell(0).setCellValue(1);
-        r.createCell(1).setCellValue(123456);
-
-        // for the streaming-variant we need to enable autosize-tracking to make it work
-        trackColumnsForAutoSizingIfSXSSF(s);
-
-        // Will be sized fairly small
-        s.autoSizeColumn((short)0);
-        s.autoSizeColumn((short)1);
-
-        // Size ranges due to different fonts on different machines
-        assertBetween("Single number column width", s.getColumnWidth(0), 350, 570);
-        assertBetween("6 digit number column width", s.getColumnWidth(1), 1500, 2100);
-
-        // Set a date format
-        CellStyle cs = wb.createCellStyle();
-        DataFormat f = wb.createDataFormat();
-        cs.setDataFormat(f.getFormat("yyyy-mm-dd MMMM hh:mm:ss"));
-        r.getCell(0).setCellStyle(cs);
-        r.getCell(1).setCellStyle(cs);
-
-        assertTrue(DateUtil.isCellDateFormatted(r.getCell(0)));
-        assertTrue(DateUtil.isCellDateFormatted(r.getCell(1)));
-
-        // Should get much bigger now
-        s.autoSizeColumn((short)0);
-        s.autoSizeColumn((short)1);
-
-        assertBetween("Date column width", s.getColumnWidth(0), 4750, 7300);
-        assertBetween("Date column width", s.getColumnWidth(1), 4750, 7300);
-
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet s = wb.createSheet("Sheet1");
+            Row r = s.createRow(0);
+            r.createCell(0).setCellValue(1);
+            r.createCell(1).setCellValue(123456);
+
+            // for the streaming-variant we need to enable autosize-tracking to make it work
+            trackColumnsForAutoSizingIfSXSSF(s);
+
+            // Will be sized fairly small
+            s.autoSizeColumn((short) 0);
+            s.autoSizeColumn((short) 1);
+
+            // Size ranges due to different fonts on different machines
+            assertBetween("Single number column width", s.getColumnWidth(0), 350, 570);
+            assertBetween("6 digit number column width", s.getColumnWidth(1), 1500, 2100);
+
+            // Set a date format
+            CellStyle cs = wb.createCellStyle();
+            DataFormat f = wb.createDataFormat();
+            cs.setDataFormat(f.getFormat("yyyy-mm-dd MMMM hh:mm:ss"));
+            r.getCell(0).setCellStyle(cs);
+            r.getCell(1).setCellStyle(cs);
+
+            assertTrue(DateUtil.isCellDateFormatted(r.getCell(0)));
+            assertTrue(DateUtil.isCellDateFormatted(r.getCell(1)));
+
+            // Should get much bigger now
+            s.autoSizeColumn((short) 0);
+            s.autoSizeColumn((short) 1);
+
+            assertBetween("Date column width", s.getColumnWidth(0), 4750, 7300);
+            assertBetween("Date column width", s.getColumnWidth(1), 4750, 7300);
+        }
     }
 }
index d040cf216f358004c28369f4429f15d3f06a2433..b36078d310a191f6fcf0ae7e1ac6d8bdb0e1a2e7 100644 (file)
@@ -23,6 +23,7 @@ import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertThrows;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
@@ -37,9 +38,7 @@ import org.apache.poi.ss.usermodel.ClientAnchor.AnchorType;
 import org.apache.poi.ss.util.CellAddress;
 import org.apache.poi.ss.util.CellRangeAddress;
 import org.apache.poi.util.NullOutputStream;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 
 public abstract class BaseTestWorkbook {
 
@@ -49,10 +48,6 @@ public abstract class BaseTestWorkbook {
         _testDataProvider = testDataProvider;
     }
 
-    @Rule
-    public ExpectedException thrown = ExpectedException.none();
-
-
     @Test
     public void sheetIterator_forEach() throws IOException {
         try (Workbook wb = _testDataProvider.createWorkbook()) {
@@ -131,14 +126,15 @@ public abstract class BaseTestWorkbook {
 
             //getting a sheet by invalid index or non-existing name
             assertNull(wb.getSheet("Sheet1"));
-            try {
-                wb.getSheetAt(0);
-                fail("should have thrown exceptiuon due to invalid sheet index");
-            } catch (IllegalArgumentException e) {
-                // expected during successful test
-                // no negative index in the range message
-                assertFalse(e.getMessage().contains("-1"));
-            }
+            IllegalArgumentException ex = assertThrows(
+                "should have thrown exception due to invalid sheet index",
+                IllegalArgumentException.class,
+                () -> wb.getSheetAt(0)
+            );
+            // expected during successful test no negative index in the range message
+            assertFalse(ex.getMessage().contains("-1"));
+
+            assertThrows(IllegalArgumentException.class, () -> wb.getSheetAt(0));
 
             Sheet sheet0 = wb.createSheet();
             Sheet sheet1 = wb.createSheet();
@@ -155,25 +151,24 @@ public abstract class BaseTestWorkbook {
             assertEquals("Sheet3", fetchedSheet.getSheetName());
             assertEquals(3, wb.getNumberOfSheets());
             assertSame(originalSheet, fetchedSheet);
-            try {
-                wb.createSheet("sHeeT3");
-                fail("should have thrown exceptiuon due to duplicate sheet name");
-            } catch (IllegalArgumentException e) {
-                // expected during successful test
-                assertEquals("The workbook already contains a sheet named 'sHeeT3'", e.getMessage());
-            }
+            ex = assertThrows(
+                "should have thrown exception due to duplicate sheet name",
+                IllegalArgumentException.class,
+                () -> wb.createSheet("sHeeT3")
+            );
+            // expected during successful test
+            assertEquals("The workbook already contains a sheet named 'sHeeT3'", ex.getMessage());
 
             //names cannot be blank or contain any of /\*?[]
             String[] invalidNames = {"", "Sheet/", "Sheet\\",
                     "Sheet?", "Sheet*", "Sheet[", "Sheet]", "'Sheet'",
                     "My:Sheet"};
             for (String sheetName : invalidNames) {
-                try {
-                    wb.createSheet(sheetName);
-                    fail("should have thrown exception due to invalid sheet name: " + sheetName);
-                } catch (IllegalArgumentException e) {
-                    // expected during successful test
-                }
+                assertThrows(
+                    "should have thrown exception due to invalid sheet name: " + sheetName,
+                    IllegalArgumentException.class,
+                    () -> wb.createSheet(sheetName)
+                );
             }
             //still have 3 sheets
             assertEquals(3, wb.getNumberOfSheets());
@@ -854,28 +849,27 @@ public abstract class BaseTestWorkbook {
 
     @Test
     public void getSheetIndex() throws IOException {
-        final Workbook wb = _testDataProvider.createWorkbook();
-        Sheet sheet1 = wb.createSheet("Sheet1");
-        Sheet sheet2 = wb.createSheet("Sheet2");
-        Sheet sheet3 = wb.createSheet("Sheet3");
-        Sheet sheet4 = wb.createSheet("Sheet4");
-
-        assertEquals(0, wb.getSheetIndex(sheet1));
-        assertEquals(1, wb.getSheetIndex(sheet2));
-        assertEquals(2, wb.getSheetIndex(sheet3));
-        assertEquals(3, wb.getSheetIndex(sheet4));
-
-        // remove sheets
-        wb.removeSheetAt(0);
-        wb.removeSheetAt(2);
-
-        // ensure that sheets are moved up and removed sheets are not found any more
-        assertEquals(-1, wb.getSheetIndex(sheet1));
-        assertEquals(0, wb.getSheetIndex(sheet2));
-        assertEquals(1, wb.getSheetIndex(sheet3));
-        assertEquals(-1, wb.getSheetIndex(sheet4));
-
-        wb.close();
+        try (Workbook wb = _testDataProvider.createWorkbook()) {
+            Sheet sheet1 = wb.createSheet("Sheet1");
+            Sheet sheet2 = wb.createSheet("Sheet2");
+            Sheet sheet3 = wb.createSheet("Sheet3");
+            Sheet sheet4 = wb.createSheet("Sheet4");
+
+            assertEquals(0, wb.getSheetIndex(sheet1));
+            assertEquals(1, wb.getSheetIndex(sheet2));
+            assertEquals(2, wb.getSheetIndex(sheet3));
+            assertEquals(3, wb.getSheetIndex(sheet4));
+
+            // remove sheets
+            wb.removeSheetAt(0);
+            wb.removeSheetAt(2);
+
+            // ensure that sheets are moved up and removed sheets are not found any more
+            assertEquals(-1, wb.getSheetIndex(sheet1));
+            assertEquals(0, wb.getSheetIndex(sheet2));
+            assertEquals(1, wb.getSheetIndex(sheet3));
+            assertEquals(-1, wb.getSheetIndex(sheet4));
+        }
     }
 
     @Test
@@ -884,9 +878,11 @@ public abstract class BaseTestWorkbook {
             Sheet sheet1 = wb.createSheet("Sheet1");
             assertNotNull(sheet1);
 
-            thrown.expect(IllegalArgumentException.class);
-            thrown.expectMessage("already contains a sheet named 'Sheet1'");
-            wb.createSheet("Sheet1");
+            IllegalArgumentException ex = assertThrows(
+                IllegalArgumentException.class,
+                () -> wb.createSheet("Sheet1")
+            );
+            assertEquals("The workbook already contains a sheet named 'Sheet1'", ex.getMessage());
         }
     }
 
index e0df851a6f22088a96d800e9a0a6598caafe69c2..7e048dbc3a418c73d3c2cca82d96eea9d3f74cb0 100644 (file)
@@ -20,23 +20,20 @@ package org.apache.poi.util;
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 
 /**
  * Class to test {@link LittleEndianInputStream} and {@link LittleEndianOutputStream}
  */
 public final class TestLittleEndianStreams {
 
-       @Rule
-       public ExpectedException thrown = ExpectedException.none();
-
        @Test
        public void testRead() throws IOException {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -95,9 +92,8 @@ public final class TestLittleEndianStreams {
                assertEquals(0x8899, lei.readUShort());
 
                // only one byte left, so this should fail
-               thrown.expect(RuntimeException.class);
-               thrown.expectMessage("Buffer overrun");
-               lei.readFully(new byte[4]);
+               RuntimeException ex = assertThrows(RuntimeException.class, () -> lei.readFully(new byte[4]));
+               assertTrue(ex.getMessage().contains("Buffer overrun"));
        }
 
        @Test
@@ -106,9 +102,8 @@ public final class TestLittleEndianStreams {
                LittleEndianInput lei = new LittleEndianByteArrayInputStream(srcBuf, 2);
 
                // only one byte left, so this should fail
-               thrown.expect(RuntimeException.class);
-               thrown.expectMessage("Buffer overrun");
-               lei.readFully(new byte[4]);
+               RuntimeException ex = assertThrows(RuntimeException.class, () -> lei.readFully(new byte[4]));
+               assertTrue(ex.getMessage().contains("Buffer overrun"));
        }
 
        @Test
@@ -117,8 +112,7 @@ public final class TestLittleEndianStreams {
                LittleEndianInput lei = new LittleEndianByteArrayInputStream(srcBuf, 2, 2);
 
                // only one byte left, so this should fail
-               thrown.expect(RuntimeException.class);
-               thrown.expectMessage("Buffer overrun");
-               lei.readFully(new byte[4]);
+               RuntimeException ex = assertThrows(RuntimeException.class, () -> lei.readFully(new byte[4]));
+               assertTrue(ex.getMessage().contains("Buffer overrun"));
        }
 }
index 47fa72dbe8996eb113b149ed93ef1a5820a60aea..ac1904dabc7f879de83230be23510821a7cfdb37 100644 (file)
@@ -19,6 +19,7 @@ package org.apache.poi.util;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThrows;
 import static org.junit.Assert.assertTrue;
 
 import java.io.File;
@@ -29,16 +30,11 @@ import java.util.Arrays;
 import org.apache.poi.poifs.dev.TestPOIFSDump;
 import org.junit.After;
 import org.junit.Before;
-import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.ExpectedException;
 
 public class TestTempFile {
     private String previousTempDir;
     private File tempDir;
-    
-    @Rule
-    public ExpectedException thrown = ExpectedException.none();
 
     @Before
     public void setUp() throws IOException {
@@ -109,14 +105,14 @@ public class TestTempFile {
         // Solution: set TempFileCreationStrategy to something that the unit test can trigger a deletion"
         assertTrue("Unable to delete temp file", tempFile.delete());
     }
-    
+
     @Test
     public void createTempFileWithDefaultSuffix() throws IOException {
         File tempFile = TempFile.createTempFile("test", null);
         assertTrue("temp file's name should end with .tmp",
                 tempFile.getName().endsWith(".tmp"));
     }
-    
+
     @Test
     public void testCreateTempDirectory() throws IOException
     {
@@ -132,11 +128,11 @@ public class TestTempFile {
         // Solution: set TempFileCreationStrategy to something that the unit test can trigger a deletion"
         assertTrue("Unable to delete tempDir", tempDir.delete());
     }
-    
+
     @Test
     public void testSetTempFileCreationStrategy() throws IOException {
         TempFile.setTempFileCreationStrategy(new DefaultTempFileCreationStrategy());
-        
+
         // Should be able to create two tempfiles with same prefix and suffix
         File file1 = TempFile.createTempFile("TestTempFile", ".tst");
         File file2 = TempFile.createTempFile("TestTempFile", ".tst");
@@ -145,9 +141,8 @@ public class TestTempFile {
         assertTrue(file2.delete());
         assertNotNull(file1);
         assertTrue(file1.delete());
-        
-        thrown.expect(IllegalArgumentException.class);
+
         //noinspection ConstantConditions
-        TempFile.setTempFileCreationStrategy(null);
+        assertThrows(IllegalArgumentException.class, () -> TempFile.setTempFileCreationStrategy(null));
     }
 }