From e10bf869eae8cd205d7a0a43395e4cf14c498587 Mon Sep 17 00:00:00 2001
From: Muthuraj Ramalingakumar <muthu90tech@gmail.com>
Date: Fri, 9 Feb 2024 03:11:32 -0800
Subject: [PATCH] ZOOKEEPER-4780: Delegate temp directory creation to Junit in
 tests.

ZOOKEEPER-4780: Delegate temp directory creation to Junit in tests.
Use Junit @TempDir annotation to manage temp directory for tests.
Use TempDir annotation for few more tests.
Remove unusedimports
There is a test which fails on the CI, but when I reran it local it passes. test=TruncateTest
Revert TruncateTest
Address comments
Make sure the temp directory scope is not affected.
fix for ZKClientConfigTest
Reviewers: ctubbsii, eolivelli
Author: muthu90tech
Closes #2100 from muthu90tech/ZOOKEEPER-4780
---
 .../zookeeper/client/ZKClientConfigTest.java  |  20 +--
 .../common/BaseX509ParameterizedTestCase.java |  11 +-
 .../common/FileChangeWatcherTest.java         |  19 +--
 .../zookeeper/common/SecretUtilsTest.java     |  10 +-
 .../org/apache/zookeeper/server/CRCTest.java  |   4 +-
 .../zookeeper/server/ClientSSLReloadTest.java |  16 +--
 .../server/DatadirCleanupManagerTest.java     |   9 +-
 .../server/PrepRequestProcessorTest.java      |   4 +-
 .../server/ZooKeeperServerBeanTest.java       |   5 +-
 .../server/ZooKeeperServerCreationTest.java   |   5 +-
 .../server/admin/JettyAdminServerTest.java    |   7 +-
 .../controller/ControllerConfigTest.java      |   6 +-
 .../server/controller/ControllerTestBase.java |  16 +--
 .../server/persistence/EmptySnapshotTest.java |   6 +-
 .../server/persistence/FileTxnLogTest.java    |  10 +-
 .../server/persistence/SnapStreamTest.java    |  44 +++---
 .../quorum/CommitProcessorMetricsTest.java    |  14 +-
 .../server/quorum/CommitProcessorTest.java    |  36 +++--
 .../server/quorum/LeaderBeanTest.java         |   5 +-
 .../server/quorum/LeaderWithObserverTest.java |   5 +-
 .../zookeeper/server/quorum/LearnerTest.java  | 134 ++++++++----------
 .../server/quorum/QuorumPeerTest.java         |   5 +-
 .../UnifiedServerSocketModeDetectionTest.java |  13 +-
 .../zookeeper/server/quorum/Zab1_0Test.java   |  51 ++++---
 .../quorum/auth/KerberosSecurityTestcase.java |  32 +----
 .../apache/zookeeper/test/ACLCountTest.java   |   4 +-
 .../org/apache/zookeeper/test/ACLTest.java    |  22 ++-
 .../zookeeper/test/ClientPortBindTest.java    |   5 +-
 .../apache/zookeeper/test/RecoveryTest.java   |   4 +-
 29 files changed, 215 insertions(+), 307 deletions(-)

diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/client/ZKClientConfigTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/client/ZKClientConfigTest.java
index d98ecba255a..588a91939e4 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/client/ZKClientConfigTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/client/ZKClientConfigTest.java
@@ -38,21 +38,12 @@
 import java.util.Properties;
 import org.apache.zookeeper.common.ZKConfig;
 import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
-import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.io.TempDir;
 
 public class ZKClientConfigTest {
 
-    private static final File testData = new File(System.getProperty("test.data.dir", "src/test/resources/data"));
-
-    @BeforeAll
-    public static void init() {
-        if (!testData.exists()) {
-            testData.mkdirs();
-        }
-    }
-
     @Test
     @Timeout(value = 10)
     public void testDefaultConfiguration() {
@@ -109,9 +100,8 @@ public void testSystemPropertyValue() {
 
     @Test
     @Timeout(value = 10)
-    public void testReadConfigurationFile() throws IOException, ConfigException {
-        File file = File.createTempFile("clientConfig", ".conf", testData);
-        file.deleteOnExit();
+    public void testReadConfigurationFile(@TempDir File testDataDir) throws IOException, ConfigException {
+        File file = File.createTempFile("clientConfig", ".conf", testDataDir);
         Properties clientConfProp = new Properties();
         clientConfProp.setProperty(ENABLE_CLIENT_SASL_KEY, "true");
         clientConfProp.setProperty(ZK_SASL_CLIENT_USERNAME, "ZK");
@@ -132,10 +122,6 @@ public void testReadConfigurationFile() throws IOException, ConfigException {
         assertEquals(conf.getProperty(LOGIN_CONTEXT_NAME_KEY), "MyClient");
         assertEquals(conf.getProperty(ZOOKEEPER_SERVER_REALM), "HADOOP.COM");
         assertEquals(conf.getProperty("dummyProperty"), "dummyValue");
-
-        // try to delete it now as we have done with the created file, why to
-        // wait for deleteOnExit() deletion
-        file.delete();
     }
 
     @Test
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/BaseX509ParameterizedTestCase.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/BaseX509ParameterizedTestCase.java
index 344faef566d..b5ece888505 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/BaseX509ParameterizedTestCase.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/BaseX509ParameterizedTestCase.java
@@ -19,18 +19,16 @@
 package org.apache.zookeeper.common;
 
 import java.io.File;
-import java.io.IOException;
 import java.security.Security;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.stream.Stream;
-import org.apache.commons.io.FileUtils;
 import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.test.ClientBase;
 import org.bouncycastle.jce.provider.BouncyCastleProvider;
 import org.junit.jupiter.api.AfterAll;
 import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.io.TempDir;
 import org.junit.jupiter.params.provider.Arguments;
 
 /**
@@ -70,6 +68,7 @@ public static Stream<Arguments> data() {
      * caching makes all test cases after the first one for a given parameter combination complete almost instantly.
      */
     protected static Map<Integer, X509TestContext> cachedTestContexts;
+    @TempDir
     protected static File tempDir;
 
     protected X509TestContext x509TestContext;
@@ -78,7 +77,6 @@ public static Stream<Arguments> data() {
     public static void setUpBaseClass() throws Exception {
         Security.addProvider(new BouncyCastleProvider());
         cachedTestContexts = new HashMap<>();
-        tempDir = ClientBase.createEmptyTestDir();
     }
 
     @AfterAll
@@ -86,11 +84,6 @@ public static void cleanUpBaseClass() {
         Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
         cachedTestContexts.clear();
         cachedTestContexts = null;
-        try {
-            FileUtils.deleteDirectory(tempDir);
-        } catch (IOException e) {
-            // ignore
-        }
     }
 
     /**
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/FileChangeWatcherTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/FileChangeWatcherTest.java
index 4ae5ab68f93..4a062560edb 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/FileChangeWatcherTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/FileChangeWatcherTest.java
@@ -31,17 +31,17 @@
 import java.util.concurrent.atomic.AtomicInteger;
 import org.apache.commons.io.FileUtils;
 import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.test.ClientBase;
-import org.junit.jupiter.api.AfterAll;
 import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 public class FileChangeWatcherTest extends ZKTestCase {
 
-    private static File tempDir;
-    private static File tempFile;
+    @TempDir
+    static File tempDir;
+    static File tempFile;
 
     private static final Logger LOG = LoggerFactory.getLogger(FileChangeWatcherTest.class);
 
@@ -49,18 +49,7 @@ public class FileChangeWatcherTest extends ZKTestCase {
 
     @BeforeAll
     public static void createTempFile() throws IOException {
-        tempDir = ClientBase.createEmptyTestDir();
         tempFile = File.createTempFile("zk_test_", "", tempDir);
-        tempFile.deleteOnExit();
-    }
-
-    @AfterAll
-    public static void cleanupTempDir() {
-        try {
-            FileUtils.deleteDirectory(tempDir);
-        } catch (IOException e) {
-            // ignore
-        }
     }
 
     @Test
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/SecretUtilsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/SecretUtilsTest.java
index 796cf5f9036..9c05a7725e6 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/SecretUtilsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/SecretUtilsTest.java
@@ -21,16 +21,20 @@
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import java.io.BufferedWriter;
+import java.io.File;
 import java.io.FileWriter;
 import java.io.IOException;
-import java.nio.file.Files;
 import java.nio.file.Path;
 import org.junit.Test;
+import org.junit.jupiter.api.io.TempDir;
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.ValueSource;
 
 public class SecretUtilsTest {
 
+    @TempDir
+    static File tempDir;
+
     @ParameterizedTest
     @ValueSource (strings = {"test secret", ""})
     public void testReadSecret(final String secretTxt) throws Exception {
@@ -58,13 +62,13 @@ public void testReadSecret_fileNotExist() {
     }
 
     public static Path createSecretFile(final String secretTxt) throws IOException {
-        final Path path = Files.createTempFile("test_", ".secrete");
+        final File tempFile = File.createTempFile("test_", ".secrete", tempDir);
+        final Path path = tempFile.toPath();
 
         final BufferedWriter writer = new BufferedWriter(new FileWriter(path.toString()));
         writer.append(secretTxt);
         writer.close();
 
-        path.toFile().deleteOnExit();
         return path;
     }
 }
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/CRCTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/CRCTest.java
index 37e9b78ab9f..26e7b051a75 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/CRCTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/CRCTest.java
@@ -44,6 +44,7 @@
 import org.apache.zookeeper.server.persistence.TxnLog.TxnIterator;
 import org.apache.zookeeper.test.ClientBase;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -102,8 +103,7 @@ private boolean getCheckSum(File snapFile) throws IOException {
      * @throws Exception
      */
     @Test
-    public void testChecksums() throws Exception {
-        File tmpDir = ClientBase.createTmpDir();
+    public void testChecksums(@TempDir File tmpDir) throws Exception {
         ClientBase.setupTestEnv();
         ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
         SyncRequestProcessor.setSnapCount(150);
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ClientSSLReloadTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ClientSSLReloadTest.java
index f9996c827bd..c0c35c69579 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ClientSSLReloadTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ClientSSLReloadTest.java
@@ -43,6 +43,7 @@
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -52,8 +53,10 @@ public class ClientSSLReloadTest extends ZKTestCase {
     private X509TestContext x509TestContext1;
     private X509TestContext x509TestContext2;
 
-    private File dir1;
-    private File dir2;
+    @TempDir
+    File dir1;
+    @TempDir
+    File dir2;
 
     private File keyStoreFile1;
     private File trustStoreFile1;
@@ -64,9 +67,6 @@ public class ClientSSLReloadTest extends ZKTestCase {
     @BeforeEach
     public void setup() throws Exception {
 
-        dir1 = ClientBase.createEmptyTestDir();
-        dir2 = ClientBase.createEmptyTestDir();
-
         Security.addProvider(new BouncyCastleProvider());
 
         x509TestContext1 = X509TestContext.newBuilder()
@@ -92,12 +92,6 @@ public void setup() throws Exception {
 
     @AfterEach
     public void teardown() throws Exception {
-        try {
-            FileUtils.deleteDirectory(dir1);
-            FileUtils.deleteDirectory(dir2);
-        } catch (IOException e) {
-            // ignore
-        }
         Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
     }
 
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DatadirCleanupManagerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DatadirCleanupManagerTest.java
index 0e85cf97834..566e540be2a 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DatadirCleanupManagerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DatadirCleanupManagerTest.java
@@ -24,22 +24,23 @@
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import java.io.File;
 import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.test.ClientBase;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 
 public class DatadirCleanupManagerTest extends ZKTestCase {
 
     private DatadirCleanupManager purgeMgr;
+    @TempDir
+    File tmpDir;
     private File snapDir;
     private File dataLogDir;
 
     @BeforeEach
     public void setUp() throws Exception {
-        File dataDir = ClientBase.createTmpDir();
-        snapDir = dataDir;
-        dataLogDir = dataDir;
+        snapDir = tmpDir;
+        dataLogDir = tmpDir;
     }
 
     @Test
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorTest.java
index e2416415807..3cf993abbb3 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorTest.java
@@ -64,6 +64,7 @@
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 
 
 public class PrepRequestProcessorTest extends ClientBase {
@@ -81,8 +82,7 @@ public class PrepRequestProcessorTest extends ClientBase {
     private boolean isStandaloneEnabledPreviously;
 
     @BeforeEach
-    public void setup() throws Exception {
-        File tmpDir = ClientBase.createTmpDir();
+    public void setup(@TempDir File tmpDir) throws Exception {
         ClientBase.setupTestEnv();
         zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
         SyncRequestProcessor.setSnapCount(100);
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java
index 90220371629..769111bce41 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java
@@ -27,12 +27,12 @@
 import org.apache.jute.Record;
 import org.apache.zookeeper.ZooDefs;
 import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
-import org.apache.zookeeper.test.ClientBase;
 import org.apache.zookeeper.txn.SetDataTxn;
 import org.apache.zookeeper.txn.TxnHeader;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 
 public class ZooKeeperServerBeanTest {
 
@@ -47,9 +47,8 @@ public void teardown() throws Exception {
     }
 
     @Test
-    public void testTxnLogElapsedSyncTime() throws IOException {
+    public void testTxnLogElapsedSyncTime(@TempDir File tmpDir) throws IOException {
 
-        File tmpDir = ClientBase.createEmptyTestDir();
         FileTxnSnapLog fileTxnSnapLog = new FileTxnSnapLog(new File(tmpDir, "data"), new File(tmpDir, "data_txnlog"));
 
         ZooKeeperServer zks = new ZooKeeperServer();
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerCreationTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerCreationTest.java
index 6c22091f426..6dd27d49438 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerCreationTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerCreationTest.java
@@ -21,8 +21,8 @@
 import java.io.File;
 import org.apache.zookeeper.proto.ConnectRequest;
 import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
-import org.apache.zookeeper.test.ClientBase;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 
 public class ZooKeeperServerCreationTest {
 
@@ -31,8 +31,7 @@ public class ZooKeeperServerCreationTest {
      * that all needed fields are initialized properly, etc.
      */
     @Test
-    public void testDefaultConstructor() throws Exception {
-        File tmpDir = ClientBase.createEmptyTestDir();
+    public void testDefaultConstructor(@TempDir File tmpDir) throws Exception {
         FileTxnSnapLog fileTxnSnapLog = new FileTxnSnapLog(new File(tmpDir, "data"), new File(tmpDir, "data_txnlog"));
 
         ZooKeeperServer zks = new ZooKeeperServer() {
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/JettyAdminServerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/JettyAdminServerTest.java
index 41f00751a7e..8ef7e8b5f96 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/JettyAdminServerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/JettyAdminServerTest.java
@@ -54,6 +54,7 @@
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -73,14 +74,12 @@ public void enableServer() {
     }
 
     @BeforeEach
-    public void setupEncryption() {
+    public void setupEncryption(@TempDir File tempDir) {
         Security.addProvider(new BouncyCastleProvider());
-        File tmpDir = null;
         X509TestContext x509TestContext = null;
         try {
-            tmpDir = ClientBase.createEmptyTestDir();
             x509TestContext = X509TestContext.newBuilder()
-                                             .setTempDir(tmpDir)
+                                             .setTempDir(tempDir)
                                              .setKeyStorePassword("")
                                              .setKeyStoreKeyType(X509KeyType.EC)
                                              .setTrustStorePassword("")
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/controller/ControllerConfigTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/controller/ControllerConfigTest.java
index 2a8ec822d48..5d2c47e9d36 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/controller/ControllerConfigTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/controller/ControllerConfigTest.java
@@ -30,8 +30,12 @@
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.jupiter.api.io.TempDir;
 
 public class ControllerConfigTest {
+
+    @TempDir
+    static File configDir;
     File configFile;
 
     private static final int AnyTickTime = 1234;
@@ -39,7 +43,7 @@ public class ControllerConfigTest {
     private static final String AnyDataDir = "temp";
 
     public static File createTempFile() throws IOException {
-        return File.createTempFile("temp", "cfg", new File(System.getProperty("user.dir")));
+        return File.createTempFile("temp", "cfg", configDir);
     }
 
     public static List<Integer> findNAvailablePorts(int n) throws IOException {
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/controller/ControllerTestBase.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/controller/ControllerTestBase.java
index 70067c77a7f..7035d54184e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/controller/ControllerTestBase.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/controller/ControllerTestBase.java
@@ -18,31 +18,25 @@
 
 package org.apache.zookeeper.server.controller;
 
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.File;
 import java.util.List;
 import java.util.concurrent.TimeoutException;
 import org.apache.zookeeper.ZKTestCase;
 import org.junit.After;
 import org.junit.Before;
+import org.junit.jupiter.api.io.TempDir;
 
 public class ControllerTestBase extends ZKTestCase {
 
     protected ControllerService controllerService;
     protected CommandClient commandClient;
-    private File tempDirectory;
     protected ControllerServerConfig config;
 
     @Before
-    public void init() throws Exception {
+    public void init(@TempDir File tempDir) throws Exception {
         List<Integer> openPorts = ControllerConfigTest.findNAvailablePorts(2);
-        File tmpFile = File.createTempFile("test", ".junit", testBaseDir);
-        tempDirectory = new File(tmpFile + ".dir");
-        assertFalse(tempDirectory.exists());
-        assertTrue(tempDirectory.mkdirs());
 
-        config = new ControllerServerConfig(openPorts.get(0), openPorts.get(1), tempDirectory.getAbsolutePath());
+        config = new ControllerServerConfig(openPorts.get(0), openPorts.get(1), tempDir.getAbsolutePath());
         controllerService = new ControllerService();
         controllerService.start(config);
 
@@ -70,9 +64,5 @@ public void cleanup() throws InterruptedException {
         if (commandClient != null) {
             commandClient.close();
         }
-
-        if (tempDirectory != null) {
-            tempDirectory.delete();
-        }
     }
 }
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/EmptySnapshotTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/EmptySnapshotTest.java
index e636b23dd3f..8d2dba45180 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/EmptySnapshotTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/EmptySnapshotTest.java
@@ -28,6 +28,7 @@
 import java.util.concurrent.ConcurrentHashMap;
 import org.apache.zookeeper.server.DataTree;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 
 /**
  * This test checks that the server does not create empty snapshot files if the
@@ -35,6 +36,9 @@
  */
 public class EmptySnapshotTest {
 
+    @TempDir
+    public static File testDir;
+
     static class MockFileSnap extends FileSnap {
 
         MockFileSnap(File snapDir) {
@@ -51,7 +55,7 @@ public synchronized void serialize(DataTree dt, Map<Long, Integer> sessions, Fil
 
     @Test
     public void testNoEmptySnapshot() throws Exception {
-        File tmpFile = File.createTempFile("empty-snapshot-test", ".junit", new File(System.getProperty("build.test.dir", "build")));
+        File tmpFile = File.createTempFile("empty-snapshot-test", ".junit", testDir);
         File tmpDataDir = new File(tmpFile + ".dir");
         assertFalse(tmpDataDir.exists());
         assertTrue(tmpDataDir.mkdirs());
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnLogTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnLogTest.java
index 3d44af73f7b..f3c2dfee2a0 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnLogTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnLogTest.java
@@ -48,6 +48,7 @@
 import org.apache.zookeeper.txn.CreateTxn;
 import org.apache.zookeeper.txn.TxnHeader;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -84,8 +85,7 @@ public void testFileSizeGreaterThanPosition() {
     }
 
     @Test
-    public void testPreAllocSizeSmallerThanTxnData() throws IOException {
-        File logDir = ClientBase.createTmpDir();
+    public void testPreAllocSizeSmallerThanTxnData(@TempDir File logDir) throws IOException {
         FileTxnLog fileTxnLog = new FileTxnLog(logDir);
 
         // Set a small preAllocSize (.5 MB)
@@ -176,9 +176,8 @@ public void testSyncThresholdExceedCount() throws IOException {
      * Test that log size get update correctly
      */
     @Test
-    public void testGetCurrentLogSize() throws Exception {
+    public void testGetCurrentLogSize(@TempDir File tmpDir) throws Exception {
         FileTxnLog.setTxnLogSizeLimit(-1);
-        File tmpDir = ClientBase.createTmpDir();
         FileTxnLog log = new FileTxnLog(tmpDir);
         FileTxnLog.setPreallocSize(PREALLOCATE);
         CreateRequest record = new CreateRequest(null, new byte[NODE_SIZE], ZooDefs.Ids.OPEN_ACL_UNSAFE, 0);
@@ -228,8 +227,7 @@ public void testGetCurrentLogSize() throws Exception {
      * txnlogs per snapshot
      */
     @Test
-    public void testLogSizeLimit() throws Exception {
-        File tmpDir = ClientBase.createTmpDir();
+    public void testLogSizeLimit(@TempDir File tmpDir) throws Exception {
         ClientBase.setupTestEnv();
 
         // Need to override preallocate set by setupTestEnv()
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/SnapStreamTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/SnapStreamTest.java
index 9292c38b3b4..f56dcfab296 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/SnapStreamTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/SnapStreamTest.java
@@ -18,7 +18,6 @@
 
 package org.apache.zookeeper.server.persistence;
 
-import static org.apache.zookeeper.test.ClientBase.createTmpDir;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -34,6 +33,7 @@
 import org.apache.zookeeper.server.persistence.SnapStream.StreamMode;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 
 public class SnapStreamTest {
 
@@ -64,30 +64,29 @@ public void testGetStreamMode() {
     }
 
     @Test
-    public void testSerializeDeserializeWithChecked() throws IOException {
-        testSerializeDeserialize(StreamMode.CHECKED, "");
+    public void testSerializeDeserializeWithChecked(@TempDir File tmpDir) throws IOException {
+        testSerializeDeserialize(StreamMode.CHECKED, "", tmpDir);
     }
 
     @Test
-    public void testSerializeDeserializeWithSNAPPY() throws IOException {
-        testSerializeDeserialize(StreamMode.SNAPPY, ".snappy");
+    public void testSerializeDeserializeWithSNAPPY(@TempDir File tmpDir) throws IOException {
+        testSerializeDeserialize(StreamMode.SNAPPY, ".snappy", tmpDir);
     }
 
     @Test
-    public void testSerializeDeserializeWithGZIP() throws IOException {
-        testSerializeDeserialize(StreamMode.GZIP, ".gz");
+    public void testSerializeDeserializeWithGZIP(@TempDir File tmpDir) throws IOException {
+        testSerializeDeserialize(StreamMode.GZIP, ".gz", tmpDir);
     }
 
-    private void testSerializeDeserialize(StreamMode mode, String fileSuffix) throws IOException {
-        testSerializeDeserialize(mode, fileSuffix, false);
-        testSerializeDeserialize(mode, fileSuffix, true);
+    private void testSerializeDeserialize(StreamMode mode, String fileSuffix, File tmpDir) throws IOException {
+        testSerializeDeserialize(mode, fileSuffix, false, tmpDir);
+        testSerializeDeserialize(mode, fileSuffix, true, tmpDir);
     }
 
-    private void testSerializeDeserialize(StreamMode mode, String fileSuffix, boolean fsync) throws IOException {
+    private void testSerializeDeserialize(StreamMode mode, String fileSuffix, boolean fsync, File tmpDir) throws IOException {
         SnapStream.setStreamMode(mode);
 
         // serialize with gzip stream
-        File tmpDir = createTmpDir();
         File file = new File(tmpDir, "snapshot.180000e3a2" + fileSuffix);
         CheckedOutputStream os = SnapStream.getOutputStream(file, fsync);
         OutputArchive oa = BinaryOutputArchive.getArchive(os);
@@ -108,12 +107,11 @@ private void testSerializeDeserialize(StreamMode mode, String fileSuffix, boolea
         SnapStream.checkSealIntegrity(is, ia);
     }
 
-    private void checkInvalidSnapshot(String filename, boolean fsync) throws IOException {
+    private void checkInvalidSnapshot(String filename, boolean fsync, File tmpDir) throws IOException {
         // set the output stream mode to CHECKED
         SnapStream.setStreamMode(StreamMode.CHECKED);
 
         // serialize to CHECKED file without magic header
-        File tmpDir = createTmpDir();
         File file = new File(tmpDir, filename);
         OutputStream os = SnapStream.getOutputStream(file, fsync);
         os.write(1);
@@ -122,18 +120,22 @@ private void checkInvalidSnapshot(String filename, boolean fsync) throws IOExcep
         assertFalse(SnapStream.isValidSnapshot(file));
     }
 
-    private void checkInvalidSnapshot(String filename) throws IOException {
-        checkInvalidSnapshot(filename, false);
-        checkInvalidSnapshot(filename, true);
+    private void checkInvalidSnapshot(String filename, File tmpDir) throws IOException {
+        checkInvalidSnapshot(filename, false, tmpDir);
+        checkInvalidSnapshot(filename, true, tmpDir);
     }
 
+    /*
+        For this test a single tempDirectory will be created but the checkInvalidsnapshot will create
+        multiple files within the directory for the tests.
+     */
     @Test
-    public void testInvalidSnapshot() throws IOException {
+    public void testInvalidSnapshot(@TempDir File tmpDir) throws IOException {
         assertFalse(SnapStream.isValidSnapshot(null));
 
-        checkInvalidSnapshot("snapshot.180000e3a2");
-        checkInvalidSnapshot("snapshot.180000e3a2.gz");
-        checkInvalidSnapshot("snapshot.180000e3a2.snappy");
+        checkInvalidSnapshot("snapshot.180000e3a2", tmpDir);
+        checkInvalidSnapshot("snapshot.180000e3a2.gz", tmpDir);
+        checkInvalidSnapshot("snapshot.180000e3a2.snappy", tmpDir);
     }
 
 }
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorMetricsTest.java
index 4a45983555a..bfa3fb78613 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorMetricsTest.java
@@ -48,7 +48,7 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
     CountDownLatch requestScheduled = null;
     CountDownLatch requestProcessed = null;
     CountDownLatch commitSeen = null;
-    CountDownLatch poolEmpytied = null;
+    CountDownLatch poolEmptied = null;
 
     @BeforeEach
     public void setup() {
@@ -126,8 +126,8 @@ protected void waitForEmptyPool() throws InterruptedException {
                 commitSeen.countDown();
             }
             super.waitForEmptyPool();
-            if (poolEmpytied != null) {
-                poolEmpytied.countDown();
+            if (poolEmptied != null) {
+                poolEmptied.countDown();
             }
         }
 
@@ -365,9 +365,9 @@ public void testTimeWaitingEmptyPoolInCommitProcessorRead() throws Exception {
         requestScheduled.await(5, TimeUnit.SECONDS);
 
         //add a commit request to trigger waitForEmptyPool
-        poolEmpytied = new CountDownLatch(1);
+        poolEmptied = new CountDownLatch(1);
         commitProcessor.commit(createWriteRequest(1L, 1));
-        poolEmpytied.await(5, TimeUnit.SECONDS);
+        poolEmptied.await(5, TimeUnit.SECONDS);
 
         long actual = (long) MetricsUtils.currentServerMetrics().get("max_time_waiting_empty_pool_in_commit_processor_read_ms");
         //since each request takes 1000ms to process, so the waiting shouldn't be more than three times of that
@@ -387,9 +387,9 @@ public void testConcurrentRequestProcessingInCommitProcessor() throws Exception
         requestScheduled.await(5, TimeUnit.SECONDS);
 
         //add a commit request to trigger waitForEmptyPool, which will record number of requests being proccessed
-        poolEmpytied = new CountDownLatch(1);
+        poolEmptied = new CountDownLatch(1);
         commitProcessor.commit(createWriteRequest(1L, 1));
-        poolEmpytied.await(5, TimeUnit.SECONDS);
+        poolEmptied.await(5, TimeUnit.SECONDS);
 
         //this will change after we upstream batch write in CommitProcessor
         Map<String, Object> values = MetricsUtils.currentServerMetrics();
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorTest.java
index 2de0987afed..2377dc77fae 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorTest.java
@@ -47,6 +47,7 @@
 import org.apache.zookeeper.test.ClientBase;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -80,14 +81,12 @@ public class CommitProcessorTest extends ZKTestCase {
 
     boolean stopped;
     TestZooKeeperServer zks;
-    File tmpDir;
     ArrayList<TestClientThread> testClients = new ArrayList<>();
     CommitProcessor commitProcessor;
 
-    public void setUp(int numCommitThreads, int numClientThreads, int writePercent) throws Exception {
+    public void setUp(int numCommitThreads, int numClientThreads, int writePercent, File tmpDir) throws Exception {
         stopped = false;
         System.setProperty(CommitProcessor.ZOOKEEPER_COMMIT_PROC_NUM_WORKER_THREADS, Integer.toString(numCommitThreads));
-        tmpDir = ClientBase.createTmpDir();
         ClientBase.setupTestEnv();
         zks = new TestZooKeeperServer(tmpDir, tmpDir, 4000);
         zks.startup();
@@ -102,10 +101,10 @@ public void setUp(
         int numCommitThreads,
         int numReadOnlyClientThreads,
         int mixWorkloadClientThreads,
-        int writePercent) throws Exception {
+        int writePercent,
+        File tmpDir) throws Exception {
         stopped = false;
         System.setProperty(CommitProcessor.ZOOKEEPER_COMMIT_PROC_NUM_WORKER_THREADS, Integer.toString(numCommitThreads));
-        tmpDir = ClientBase.createTmpDir();
         ClientBase.setupTestEnv();
         zks = new TestZooKeeperServer(tmpDir, tmpDir, 4000);
         zks.startup();
@@ -131,9 +130,6 @@ public void tearDown() throws Exception {
             client.interrupt();
             client.join();
         }
-        if (tmpDir != null) {
-            assertTrue(ClientBase.recursiveDelete(tmpDir), "delete " + tmpDir.toString());
-        }
         processedReadRequests.set(0);
         processedWriteRequests.set(0);
         testClients.clear();
@@ -199,10 +195,10 @@ public void run() {
     }
 
     @Test
-    public void testNoCommitWorkersReadOnlyWorkload() throws Exception {
+    public void testNoCommitWorkersReadOnlyWorkload(@TempDir File tmpDir) throws Exception {
         int numClients = 10;
         LOG.info("testNoCommitWorkersReadOnlyWorkload");
-        setUp(0, numClients, 0);
+        setUp(0, numClients, 0, tmpDir);
         synchronized (this) {
             wait(TEST_RUN_TIME_IN_MS);
         }
@@ -213,10 +209,10 @@ public void testNoCommitWorkersReadOnlyWorkload() throws Exception {
     }
 
     @Test
-    public void testNoCommitWorkersMixedWorkload() throws Exception {
+    public void testNoCommitWorkersMixedWorkload(@TempDir File tmpDir) throws Exception {
         int numClients = 10;
         LOG.info("testNoCommitWorkersMixedWorkload 25w/75r workload test");
-        setUp(0, numClients, 25);
+        setUp(0, numClients, 25, tmpDir);
         synchronized (this) {
             wait(TEST_RUN_TIME_IN_MS);
         }
@@ -225,10 +221,10 @@ public void testNoCommitWorkersMixedWorkload() throws Exception {
     }
 
     @Test
-    public void testOneCommitWorkerReadOnlyWorkload() throws Exception {
+    public void testOneCommitWorkerReadOnlyWorkload(@TempDir File tmpDir) throws Exception {
         int numClients = 10;
         LOG.info("testOneCommitWorkerReadOnlyWorkload");
-        setUp(1, numClients, 0);
+        setUp(1, numClients, 0, tmpDir);
         synchronized (this) {
             wait(TEST_RUN_TIME_IN_MS);
         }
@@ -239,8 +235,8 @@ public void testOneCommitWorkerReadOnlyWorkload() throws Exception {
     }
 
     @Test
-    public void testOneCommitWorkerMixedWorkload() throws Exception {
-        setUp(1, 10, 25);
+    public void testOneCommitWorkerMixedWorkload(@TempDir File tmpDir) throws Exception {
+        setUp(1, 10, 25, tmpDir);
         LOG.info("testOneCommitWorkerMixedWorkload 25w/75r workload test");
         synchronized (this) {
             wait(TEST_RUN_TIME_IN_MS);
@@ -250,10 +246,10 @@ public void testOneCommitWorkerMixedWorkload() throws Exception {
     }
 
     @Test
-    public void testManyCommitWorkersReadOnly() throws Exception {
+    public void testManyCommitWorkersReadOnly(@TempDir File tmpDir) throws Exception {
         int numClients = 10;
         LOG.info("testManyCommitWorkersReadOnly");
-        setUp(10, numClients, 0);
+        setUp(10, numClients, 0, tmpDir);
         synchronized (this) {
             wait(TEST_RUN_TIME_IN_MS);
         }
@@ -264,8 +260,8 @@ public void testManyCommitWorkersReadOnly() throws Exception {
     }
 
     @Test
-    public void testManyCommitWorkersMixedWorkload() throws Exception {
-        setUp(16, 8, 8, 25);
+    public void testManyCommitWorkersMixedWorkload(@TempDir File tmpDir) throws Exception {
+        setUp(16, 8, 8, 25, tmpDir);
         LOG.info("testManyCommitWorkersMixedWorkload 8X0w/100r + 8X25w/75r workload test");
         synchronized (this) {
             wait(TEST_RUN_TIME_IN_MS);
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderBeanTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderBeanTest.java
index 4d3c6fba752..12fe04166f8 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderBeanTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderBeanTest.java
@@ -43,11 +43,11 @@
 import org.apache.zookeeper.server.quorum.QuorumPeer.LearnerType;
 import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
 import org.apache.zookeeper.server.quorum.flexible.QuorumVerifier;
-import org.apache.zookeeper.test.ClientBase;
 import org.apache.zookeeper.txn.TxnHeader;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 import org.mockito.Mockito;
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
@@ -60,6 +60,8 @@ public class LeaderBeanTest {
     private LeaderZooKeeperServer zks;
     private QuorumPeer qp;
     private QuorumVerifier quorumVerifierMock;
+    @TempDir
+    File tmpDir;
 
     public static Map<Long, QuorumServer> getMockedPeerViews(long myId) {
         int clientPort = PortAssignment.unique();
@@ -80,7 +82,6 @@ public void setUp() throws IOException, X509Exception {
         when(quorumVerifierMock.getAllMembers()).thenReturn(getMockedPeerViews(qp.getMyId()));
 
         qp.setQuorumVerifier(quorumVerifierMock, false);
-        File tmpDir = ClientBase.createEmptyTestDir();
         fileTxnSnapLog = new FileTxnSnapLog(new File(tmpDir, "data"), new File(tmpDir, "data_txnlog"));
         ZKDatabase zkDb = new ZKDatabase(fileTxnSnapLog);
 
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderWithObserverTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderWithObserverTest.java
index 7ac563698b5..f9de4518344 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderWithObserverTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderWithObserverTest.java
@@ -29,22 +29,22 @@
 import java.util.Map;
 import java.util.Set;
 import org.apache.zookeeper.PortAssignment;
-import org.apache.zookeeper.test.ClientBase;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 
 public class LeaderWithObserverTest {
 
     QuorumPeer peer;
     Leader leader;
+    @TempDir
     File tmpDir;
     long participantId;
     long observerId;
 
     @BeforeEach
     public void setUp() throws Exception {
-        tmpDir = ClientBase.createTmpDir();
         peer = createQuorumPeer(tmpDir);
         participantId = 1;
         Map<Long, QuorumPeer.QuorumServer> peers = peer.getQuorumVerifier().getAllMembers();
@@ -60,7 +60,6 @@ public void setUp() throws Exception {
     @AfterEach
     public void tearDown() {
         leader.shutdown("end of test");
-        tmpDir.delete();
     }
 
     @Test
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerTest.java
index d876c167f94..d64d051b093 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerTest.java
@@ -50,12 +50,12 @@
 import org.apache.zookeeper.server.ExitCode;
 import org.apache.zookeeper.server.ZKDatabase;
 import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
-import org.apache.zookeeper.test.TestUtils;
 import org.apache.zookeeper.txn.CreateTxn;
 import org.apache.zookeeper.txn.TxnHeader;
 import org.apache.zookeeper.util.ServiceUtils;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 
 public class LearnerTest extends ZKTestCase {
 
@@ -269,56 +269,52 @@ public void connectToLearnerMasterLimitTest() throws Exception {
     }
 
     @Test
-    public void syncTest() throws Exception {
-        File tmpFile = File.createTempFile("test", ".dir", testData);
+    public void syncTest(@TempDir File tmpDir) throws Exception {
+        File tmpFile = File.createTempFile("test", ".dir", tmpDir);
         tmpFile.delete();
-        try {
-            FileTxnSnapLog ftsl = new FileTxnSnapLog(tmpFile, tmpFile);
-            SimpleLearner sl = new SimpleLearner(ftsl);
-            long startZxid = sl.zk.getLastProcessedZxid();
-
-            // Set up bogus streams
-            ByteArrayOutputStream baos = new ByteArrayOutputStream();
-            BinaryOutputArchive oa = BinaryOutputArchive.getArchive(baos);
-            sl.leaderOs = BinaryOutputArchive.getArchive(new ByteArrayOutputStream());
-
-            // make streams and socket do something innocuous
-            sl.bufferedOutput = new BufferedOutputStream(System.out);
-            sl.sock = new Socket();
-
-            // fake messages from the server
-            QuorumPacket qp = new QuorumPacket(Leader.SNAP, 0, null, null);
-            oa.writeRecord(qp, null);
-            sl.zk.getZKDatabase().serializeSnapshot(oa);
-            oa.writeString("BenWasHere", "signature");
-            TxnHeader hdr = new TxnHeader(0, 0, 0, 0, ZooDefs.OpCode.create);
-            CreateTxn txn = new CreateTxn("/foo", new byte[0], new ArrayList<ACL>(), false, sl.zk.getZKDatabase().getNode("/").stat.getCversion());
-            ByteArrayOutputStream tbaos = new ByteArrayOutputStream();
-            BinaryOutputArchive boa = BinaryOutputArchive.getArchive(tbaos);
-            hdr.serialize(boa, "hdr");
-            txn.serialize(boa, "txn");
-            tbaos.close();
-            qp = new QuorumPacket(Leader.PROPOSAL, 1, tbaos.toByteArray(), null);
-            oa.writeRecord(qp, null);
-
-            // setup the messages to be streamed to follower
-            sl.leaderIs = BinaryInputArchive.getArchive(new ByteArrayInputStream(baos.toByteArray()));
-
-            try {
-                sl.syncWithLeader(3);
-            } catch (EOFException e) {
-            }
+        FileTxnSnapLog ftsl = new FileTxnSnapLog(tmpFile, tmpFile);
+        SimpleLearner sl = new SimpleLearner(ftsl);
+        long startZxid = sl.zk.getLastProcessedZxid();
+
+        // Set up bogus streams
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        BinaryOutputArchive oa = BinaryOutputArchive.getArchive(baos);
+        sl.leaderOs = BinaryOutputArchive.getArchive(new ByteArrayOutputStream());
+
+        // make streams and socket do something innocuous
+        sl.bufferedOutput = new BufferedOutputStream(System.out);
+        sl.sock = new Socket();
+
+        // fake messages from the server
+        QuorumPacket qp = new QuorumPacket(Leader.SNAP, 0, null, null);
+        oa.writeRecord(qp, null);
+        sl.zk.getZKDatabase().serializeSnapshot(oa);
+        oa.writeString("BenWasHere", "signature");
+        TxnHeader hdr = new TxnHeader(0, 0, 0, 0, ZooDefs.OpCode.create);
+        CreateTxn txn = new CreateTxn("/foo", new byte[0], new ArrayList<ACL>(), false, sl.zk.getZKDatabase().getNode("/").stat.getCversion());
+        ByteArrayOutputStream tbaos = new ByteArrayOutputStream();
+        BinaryOutputArchive boa = BinaryOutputArchive.getArchive(tbaos);
+        hdr.serialize(boa, "hdr");
+        txn.serialize(boa, "txn");
+        tbaos.close();
+        qp = new QuorumPacket(Leader.PROPOSAL, 1, tbaos.toByteArray(), null);
+        oa.writeRecord(qp, null);
+
+        // setup the messages to be streamed to follower
+        sl.leaderIs = BinaryInputArchive.getArchive(new ByteArrayInputStream(baos.toByteArray()));
 
-            sl.zk.shutdown();
-            sl = new SimpleLearner(ftsl);
-            assertEquals(startZxid, sl.zk.getLastProcessedZxid());
-        } finally {
-            TestUtils.deleteFileRecursively(tmpFile);
+        try {
+            sl.syncWithLeader(3);
+        } catch (EOFException e) {
         }
+
+        sl.zk.shutdown();
+        sl = new SimpleLearner(ftsl);
+        assertEquals(startZxid, sl.zk.getLastProcessedZxid());
     }
 
     @Test
-    public void truncFailTest() throws Exception {
+    public void truncFailTest(@TempDir File tmpDir) throws Exception {
         final boolean[] exitProcCalled = {false};
 
         ServiceUtils.setSystemExitProcedure(new Consumer<Integer>() {
@@ -329,39 +325,35 @@ public void accept(Integer exitCode) {
             }
         });
 
-        File tmpFile = File.createTempFile("test", ".dir", testData);
+        File tmpFile = File.createTempFile("test", ".dir", tmpDir);
         tmpFile.delete();
-        try {
-            FileTxnSnapLog txnSnapLog = new FileTxnSnapLog(tmpFile, tmpFile);
-            SimpleLearner sl = new SimpleLearner(txnSnapLog);
-            long startZxid = sl.zk.getLastProcessedZxid();
+        FileTxnSnapLog txnSnapLog = new FileTxnSnapLog(tmpFile, tmpFile);
+        SimpleLearner sl = new SimpleLearner(txnSnapLog);
+        long startZxid = sl.zk.getLastProcessedZxid();
 
-            // Set up bogus streams
-            ByteArrayOutputStream baos = new ByteArrayOutputStream();
-            BinaryOutputArchive oa = BinaryOutputArchive.getArchive(baos);
-            sl.leaderOs = BinaryOutputArchive.getArchive(new ByteArrayOutputStream());
+        // Set up bogus streams
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        BinaryOutputArchive oa = BinaryOutputArchive.getArchive(baos);
+        sl.leaderOs = BinaryOutputArchive.getArchive(new ByteArrayOutputStream());
 
-            // make streams and socket do something innocuous
-            sl.bufferedOutput = new BufferedOutputStream(System.out);
-            sl.sock = new Socket();
+        // make streams and socket do something innocuous
+        sl.bufferedOutput = new BufferedOutputStream(System.out);
+        sl.sock = new Socket();
 
-            // fake messages from the server
-            QuorumPacket qp = new QuorumPacket(Leader.TRUNC, 0, null, null);
-            oa.writeRecord(qp, null);
+        // fake messages from the server
+        QuorumPacket qp = new QuorumPacket(Leader.TRUNC, 0, null, null);
+        oa.writeRecord(qp, null);
 
-            // setup the messages to be streamed to follower
-            sl.leaderIs = BinaryInputArchive.getArchive(new ByteArrayInputStream(baos.toByteArray()));
+        // setup the messages to be streamed to follower
+        sl.leaderIs = BinaryInputArchive.getArchive(new ByteArrayInputStream(baos.toByteArray()));
 
-            try {
-                sl.syncWithLeader(3);
-            } catch (EOFException e) {
-            }
+        try {
+            sl.syncWithLeader(3);
+        } catch (EOFException e) {
+        }
 
-            sl.zk.shutdown();
+        sl.zk.shutdown();
 
-            assertThat("System.exit() should have been called", exitProcCalled[0], is(true));
-        } finally {
-            TestUtils.deleteFileRecursively(tmpFile);
-        }
+        assertThat("System.exit() should have been called", exitProcCalled[0], is(true));
     }
 }
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTest.java
index b832f4f9679..65e5fa59037 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTest.java
@@ -30,8 +30,8 @@
 import org.apache.zookeeper.PortAssignment;
 import org.apache.zookeeper.server.quorum.QuorumPeer.LearnerType;
 import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
-import org.apache.zookeeper.test.ClientBase;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 
 public class QuorumPeerTest {
 
@@ -45,9 +45,8 @@ public class QuorumPeerTest {
      * Test case for https://issues.apache.org/jira/browse/ZOOKEEPER-2301
      */
     @Test
-    public void testQuorumPeerListendOnSpecifiedClientIP() throws IOException {
+    public void testQuorumPeerListendOnSpecifiedClientIP(@TempDir File dataDir) throws IOException {
         long myId = 1;
-        File dataDir = ClientBase.createTmpDir();
         int clientPort = PortAssignment.unique();
         Map<Long, QuorumServer> peersView = new HashMap<>();
         InetAddress clientIP = InetAddress.getLoopbackAddress();
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketModeDetectionTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketModeDetectionTest.java
index 3400a288301..05b67debcda 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketModeDetectionTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketModeDetectionTest.java
@@ -34,7 +34,6 @@
 import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
-import org.apache.commons.io.FileUtils;
 import org.apache.zookeeper.PortAssignment;
 import org.apache.zookeeper.ZKTestCase;
 import org.apache.zookeeper.common.ClientX509Util;
@@ -42,11 +41,11 @@
 import org.apache.zookeeper.common.X509KeyType;
 import org.apache.zookeeper.common.X509TestContext;
 import org.apache.zookeeper.common.X509Util;
-import org.apache.zookeeper.test.ClientBase;
 import org.bouncycastle.jce.provider.BouncyCastleProvider;
 import org.junit.jupiter.api.AfterAll;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.io.TempDir;
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.ValueSource;
 import org.slf4j.Logger;
@@ -60,8 +59,8 @@
 public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
 
     private static final Logger LOG = LoggerFactory.getLogger(UnifiedServerSocketModeDetectionTest.class);
-
-    private static File tempDir;
+    @TempDir
+    static File tempDir;
     private static X509TestContext x509TestContext;
 
     private X509Util x509Util;
@@ -75,17 +74,11 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
     @BeforeAll
     public static void setUpClass() throws Exception {
         Security.addProvider(new BouncyCastleProvider());
-        tempDir = ClientBase.createEmptyTestDir();
         x509TestContext = X509TestContext.newBuilder().setTempDir(tempDir).setKeyStoreKeyType(X509KeyType.EC).setTrustStoreKeyType(X509KeyType.EC).build();
     }
 
     @AfterAll
     public static void tearDownClass() {
-        try {
-            FileUtils.deleteDirectory(tempDir);
-        } catch (IOException e) {
-            // ignore
-        }
         Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
     }
 
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/Zab1_0Test.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/Zab1_0Test.java
index f0db38e2675..2a4ebaa509c 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/Zab1_0Test.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/Zab1_0Test.java
@@ -69,6 +69,7 @@
 import org.apache.zookeeper.txn.TxnHeader;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -76,8 +77,6 @@ public class Zab1_0Test extends ZKTestCase {
 
     private static final Logger LOG = LoggerFactory.getLogger(Zab1_0Test.class);
 
-    private static final File testData = new File(System.getProperty("test.data.dir", "src/test/resources/data"));
-
     @BeforeEach
     public void setUp() {
         System.setProperty("zookeeper.admin.enableServer", "false");
@@ -136,7 +135,7 @@ public void run() {
 
     }
     @Test
-    public void testLeaderInConnectingFollowers() throws Exception {
+    public void testLeaderInConnectingFollowers(@TempDir File testData) throws Exception {
         File tmpDir = File.createTempFile("test", "dir", testData);
         tmpDir.delete();
         tmpDir.mkdir();
@@ -190,7 +189,7 @@ public void testLeaderInConnectingFollowers() throws Exception {
      */
 
     @Test
-    public void testLastAcceptedEpoch() throws Exception {
+    public void testLastAcceptedEpoch(@TempDir File testData) throws Exception {
         File tmpDir = File.createTempFile("test", "dir", testData);
         tmpDir.delete();
         tmpDir.mkdir();
@@ -228,7 +227,7 @@ public void testLastAcceptedEpoch() throws Exception {
     }
 
     @Test
-    public void testLeaderInElectingFollowers() throws Exception {
+    public void testLeaderInElectingFollowers(@TempDir File testData) throws Exception {
         File tmpDir = File.createTempFile("test", "dir", testData);
         tmpDir.delete();
         tmpDir.mkdir();
@@ -302,7 +301,7 @@ public interface ObserverConversation {
 
     }
 
-    public void testLeaderConversation(LeaderConversation conversation) throws Exception {
+    public void testLeaderConversation(LeaderConversation conversation, File testData) throws Exception {
         Socket[] pair = getSocketPair();
         Socket leaderSocket = pair[0];
         Socket followerSocket = pair[1];
@@ -342,7 +341,7 @@ public void testLeaderConversation(LeaderConversation conversation) throws Excep
         }
     }
 
-    public void testPopulatedLeaderConversation(PopulatedLeaderConversation conversation, int ops) throws Exception {
+    public void testPopulatedLeaderConversation(PopulatedLeaderConversation conversation, int ops, File testData) throws Exception {
         Socket[] pair = getSocketPair();
         Socket leaderSocket = pair[0];
         Socket followerSocket = pair[1];
@@ -408,7 +407,7 @@ public void testPopulatedLeaderConversation(PopulatedLeaderConversation conversa
         }
     }
 
-    public void testFollowerConversation(FollowerConversation conversation) throws Exception {
+    public void testFollowerConversation(FollowerConversation conversation, File testData) throws Exception {
         File tmpDir = File.createTempFile("test", "dir", testData);
         tmpDir.delete();
         tmpDir.mkdir();
@@ -458,7 +457,7 @@ public void run() {
         }
     }
 
-    public void testObserverConversation(ObserverConversation conversation) throws Exception {
+    public void testObserverConversation(ObserverConversation conversation, File testData) throws Exception {
         File tmpDir = File.createTempFile("test", "dir", testData);
         tmpDir.delete();
         tmpDir.mkdir();
@@ -508,7 +507,7 @@ public void run() {
     }
 
     @Test
-    public void testUnnecessarySnap() throws Exception {
+    public void testUnnecessarySnap(@TempDir File testData) throws Exception {
         testPopulatedLeaderConversation(new PopulatedLeaderConversation() {
             @Override
             public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l, long zxid) throws Exception {
@@ -540,7 +539,7 @@ public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l, long
                 assertEquals(Leader.DIFF, qp.getType());
 
             }
-        }, 2);
+        }, 2, testData);
     }
 
     // We want to track the change with a callback rather than depending on timing
@@ -568,7 +567,7 @@ public synchronized boolean changed() {
     }
 
     @Test
-    public void testNormalFollowerRun() throws Exception {
+    public void testNormalFollowerRun(@TempDir File testData) throws Exception {
         testFollowerConversation(new FollowerConversation() {
             @Override
             public void converseWithFollower(InputArchive ia, OutputArchive oa, Follower f) throws Exception {
@@ -698,11 +697,11 @@ private void proposeSetData(QuorumPacket qp, long zxid, String data, int version
                 boa.writeRecord(sdt, null);
                 qp.setData(baos.toByteArray());
             }
-        });
+        }, testData);
     }
 
     @Test
-    public void testNormalFollowerRunWithDiff() throws Exception {
+    public void testNormalFollowerRunWithDiff(@TempDir File testData) throws Exception {
         testFollowerConversation(new FollowerConversation() {
             @Override
             public void converseWithFollower(InputArchive ia, OutputArchive oa, Follower f) throws Exception {
@@ -819,11 +818,11 @@ private void proposeNewSession(QuorumPacket qp, long zxid, long sessionId) throw
                 boa.writeRecord(cst, null);
                 qp.setData(baos.toByteArray());
             }
-        });
+        }, testData);
     }
 
     @Test
-    public void testNormalRun() throws Exception {
+    public void testNormalRun(@TempDir File testData) throws Exception {
         testLeaderConversation(new LeaderConversation() {
             public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) throws IOException {
                 assertEquals(0, l.self.getAcceptedEpoch());
@@ -861,11 +860,11 @@ public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) thro
                 readPacketSkippingPing(ia, qp);
                 assertEquals(Leader.UPTODATE, qp.getType());
             }
-        });
+        }, testData);
     }
 
     @Test
-    public void testTxnTimeout() throws Exception {
+    public void testTxnTimeout(@TempDir File testData) throws Exception {
         testLeaderConversation(new LeaderConversation() {
             public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) throws IOException, InterruptedException, org.apache.zookeeper.server.quorum.Leader.XidRolloverException {
                 assertEquals(0, l.self.getAcceptedEpoch());
@@ -922,7 +921,7 @@ public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) thro
                 }
                 fail("Connection hasn't been closed by leader after transaction times out.");
             }
-        });
+        }, testData);
     }
 
     private void deserializeSnapshot(InputArchive ia) throws IOException {
@@ -933,7 +932,7 @@ private void deserializeSnapshot(InputArchive ia) throws IOException {
     }
 
     @Test
-    public void testNormalObserverRun() throws Exception {
+    public void testNormalObserverRun(@TempDir File testData) throws Exception {
         testObserverConversation(new ObserverConversation() {
             @Override
             public void converseWithObserver(InputArchive ia, OutputArchive oa, Observer o) throws Exception {
@@ -1066,11 +1065,11 @@ private void proposeSetData(QuorumPacket qp, String path, long zxid, String data
                 boa.writeRecord(sdt, null);
                 qp.setData(baos.toByteArray());
             }
-        });
+        }, testData);
     }
 
     @Test
-    public void testLeaderBehind() throws Exception {
+    public void testLeaderBehind(@TempDir File testData) throws Exception {
         testLeaderConversation(new LeaderConversation() {
             public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) throws IOException {
                 /* we test a normal run. everything should work out well. */
@@ -1098,7 +1097,7 @@ public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) thro
                 readPacketSkippingPing(ia, qp);
                 assertEquals(Leader.UPTODATE, qp.getType());
             }
-        });
+        }, testData);
     }
 
     /**
@@ -1108,7 +1107,7 @@ public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) thro
      * @throws Exception
      */
     @Test
-    public void testAbandonBeforeACKEpoch() throws Exception {
+    public void testAbandonBeforeACKEpoch(@TempDir File testData) throws Exception {
         testLeaderConversation(new LeaderConversation() {
             public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) throws IOException, InterruptedException {
                 /* we test a normal run. everything should work out well. */
@@ -1126,7 +1125,7 @@ public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) thro
                 // The leader didn't get a quorum of acks - make sure that leader's current epoch is not advanced
                 assertEquals(0, l.self.getCurrentEpoch());
             }
-        });
+        }, testData);
     }
 
     static class ConversableFollower extends Follower {
@@ -1187,7 +1186,7 @@ private String readContentsOfFile(File f) throws IOException {
     }
 
     @Test
-    public void testInitialAcceptedCurrent() throws Exception {
+    public void testInitialAcceptedCurrent(@TempDir File testData) throws Exception {
         File tmpDir = File.createTempFile("test", ".dir", testData);
         tmpDir.delete();
         tmpDir.mkdir();
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosSecurityTestcase.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosSecurityTestcase.java
index aa1b43400ce..8ab6644ddbf 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosSecurityTestcase.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosSecurityTestcase.java
@@ -18,14 +18,11 @@
 
 package org.apache.zookeeper.server.quorum.auth;
 
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.File;
-import java.io.IOException;
 import java.util.Properties;
-import org.apache.commons.io.FileUtils;
 import org.junit.jupiter.api.AfterAll;
 import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.io.TempDir;
 
 /*
  * This code is originally from HDFS, see the similarly named file there
@@ -48,7 +45,8 @@
 public class KerberosSecurityTestcase extends QuorumAuthTestBase {
 
     private static MiniKdc kdc;
-    private static File workDir;
+    @TempDir
+    static File workDir;
     private static Properties conf;
 
     @BeforeAll
@@ -59,39 +57,15 @@ public static void setUpSasl() throws Exception {
     @AfterAll
     public static void tearDownSasl() throws Exception {
         stopMiniKdc();
-        FileUtils.deleteQuietly(workDir);
     }
 
     public static void startMiniKdc() throws Exception {
-        createTestDir();
         createMiniKdcConf();
 
         kdc = new MiniKdc(conf, workDir);
         kdc.start();
     }
 
-    /**
-     * Create a working directory, it should be the build directory. Under this
-     * directory an ApacheDS working directory will be created, this directory
-     * will be deleted when the MiniKdc stops.
-     *
-     * @throws IOException
-     */
-    public static void createTestDir() throws IOException {
-        workDir = createTmpDir(new File(System.getProperty("build.test.dir", "build")));
-    }
-
-    static File createTmpDir(File parentDir) throws IOException {
-        File tmpFile = File.createTempFile("test", ".junit", parentDir);
-        // don't delete tmpFile - this ensures we don't attempt to create
-        // a tmpDir with a duplicate name
-        File tmpDir = new File(tmpFile + ".dir");
-        // never true if tmpfile does it's job
-        assertFalse(tmpDir.exists());
-        assertTrue(tmpDir.mkdirs());
-        return tmpDir;
-    }
-
     /**
      * Create a Kdc configuration
      */
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLCountTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLCountTest.java
index 2b9cc9c7b36..a81f4f1bb00 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLCountTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLCountTest.java
@@ -36,6 +36,7 @@
 import org.apache.zookeeper.server.SyncRequestProcessor;
 import org.apache.zookeeper.server.ZooKeeperServer;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -58,8 +59,7 @@ public class ACLCountTest extends ZKTestCase {
      * since there are only 2 *unique* ACL values.
      */
     @Test
-    public void testAclCount() throws Exception {
-        File tmpDir = ClientBase.createTmpDir();
+    public void testAclCount(@TempDir File tmpDir) throws Exception {
         ClientBase.setupTestEnv();
         ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
         SyncRequestProcessor.setSnapCount(1000);
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLTest.java
index 965d99c4ca7..e66592e49e9 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLTest.java
@@ -49,6 +49,7 @@
 import org.apache.zookeeper.server.ZooKeeperServer;
 import org.apache.zookeeper.server.auth.IPAuthenticationProvider;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -69,11 +70,10 @@ public void testIPAuthenticationIsValidCIDR() throws Exception {
     }
 
     @Test
-    public void testNettyIpAuthDefault() throws Exception {
+    public void testNettyIpAuthDefault(@TempDir File tmpDir) throws Exception {
         String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
         System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, "org.apache.zookeeper.server.NettyServerCnxnFactory");
         ClientBase.setupTestEnv();
-        File tmpDir = ClientBase.createTmpDir();
         ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
         SyncRequestProcessor.setSnapCount(1000);
         final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
@@ -102,8 +102,7 @@ public void testNettyIpAuthDefault() throws Exception {
     }
 
     @Test
-    public void testDisconnectedAddAuth() throws Exception {
-        File tmpDir = ClientBase.createTmpDir();
+    public void testDisconnectedAddAuth(@TempDir File tmpDir) throws Exception {
         ClientBase.setupTestEnv();
         ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
         SyncRequestProcessor.setSnapCount(1000);
@@ -133,8 +132,7 @@ public void testDisconnectedAddAuth() throws Exception {
      * node is actually working.
      */
     @Test
-    public void testAcls() throws Exception {
-        File tmpDir = ClientBase.createTmpDir();
+    public void testAcls(@TempDir File tmpDir) throws Exception {
         ClientBase.setupTestEnv();
         ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
         SyncRequestProcessor.setSnapCount(1000);
@@ -223,8 +221,7 @@ public void process(WatchedEvent event) {
     }
 
     @Test
-    public void testNullACL() throws Exception {
-        File tmpDir = ClientBase.createTmpDir();
+    public void testNullACL(@TempDir File tmpDir) throws Exception {
         ClientBase.setupTestEnv();
         ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
         final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
@@ -264,8 +261,7 @@ public void testNullACL() throws Exception {
     }
 
     @Test
-    public void testNullValueACL() throws Exception {
-        File tmpDir = ClientBase.createTmpDir();
+    public void testNullValueACL(@TempDir File tmpDir) throws Exception {
         ClientBase.setupTestEnv();
         ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
         final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
@@ -309,8 +305,7 @@ public void testNullValueACL() throws Exception {
     }
 
     @Test
-    public void testExistACLCheck() throws Exception {
-        File tmpDir = ClientBase.createTmpDir();
+    public void testExistACLCheck(@TempDir File tmpDir) throws Exception {
         ClientBase.setupTestEnv();
         ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
         final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
@@ -359,8 +354,7 @@ public void testExistACLCheck() throws Exception {
     }
 
     @Test
-    public void testExistACLCheckAtRootPath() throws Exception {
-        File tmpDir = ClientBase.createTmpDir();
+    public void testExistACLCheckAtRootPath(@TempDir File tmpDir) throws Exception {
         ClientBase.setupTestEnv();
         ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
         final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientPortBindTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientPortBindTest.java
index 767a24481ce..5061c5f4df3 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientPortBindTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientPortBindTest.java
@@ -33,6 +33,7 @@
 import org.apache.zookeeper.server.ServerCnxnFactory;
 import org.apache.zookeeper.server.ZooKeeperServer;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -44,7 +45,7 @@ public class ClientPortBindTest extends ZKTestCase {
      * Verify that the server binds to the specified address
      */
     @Test
-    public void testBindByAddress() throws Exception {
+    public void testBindByAddress(@TempDir File tmpDir) throws Exception {
         String bindAddress = null;
         Enumeration<NetworkInterface> intfs = NetworkInterface.getNetworkInterfaces();
         // if we have a loopback and it has an address use it
@@ -78,8 +79,6 @@ public void testBindByAddress() throws Exception {
         final String HOSTPORT = bindAddress + ":" + PORT;
         LOG.info("Using {} as the host/port", HOSTPORT);
 
-        File tmpDir = ClientBase.createTmpDir();
-
         ClientBase.setupTestEnv();
         ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
 
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/RecoveryTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/RecoveryTest.java
index 2f9c1e58d18..46ff5880bbb 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/RecoveryTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/RecoveryTest.java
@@ -37,6 +37,7 @@
 import org.apache.zookeeper.server.SyncRequestProcessor;
 import org.apache.zookeeper.server.ZooKeeperServer;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -61,8 +62,7 @@ public class RecoveryTest extends ZKTestCase implements Watcher {
      * that the server is down (ping) then the op will throw connectionloss.
      */
     @Test
-    public void testRecovery() throws Exception {
-        File tmpDir = ClientBase.createTmpDir();
+    public void testRecovery(@TempDir File tmpDir) throws Exception {
 
         ClientBase.setupTestEnv();
         ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);