Browse Source

ZOOKEEPER-3872: Upgrade jUnit in ZooKeeper-server

Sub-task of ZOOKEEPER-3732, updating jUnit to 5.6.2 in zookeeper-server sub-component.

Change-Id: I1fc2a7f860eae0f1d285cb278f6eca7a3b947695

Author: Tamas Penzes <tamaas@cloudera.com>

Reviewers: Mate Szalay-Beko <symat@apache.org>, Norbert Kalmar <nkalmar@apache.org>

Closes #1417 from tamaashu/ZOOKEEPER-3872
Tamas Penzes 4 năm trước cách đây
mục cha
commit
c42c8c9408
100 tập tin đã thay đổi với 2422 bổ sung2049 xóa
  1. 18 0
      pom.xml
  2. 20 0
      zookeeper-server/pom.xml
  3. 5 5
      zookeeper-server/src/test/java/org/apache/zookeeper/ClientCanonicalizeTest.java
  4. 15 13
      zookeeper-server/src/test/java/org/apache/zookeeper/ClientCnxnSocketFragilityTest.java
  5. 7 7
      zookeeper-server/src/test/java/org/apache/zookeeper/ClientCnxnSocketTest.java
  6. 2 2
      zookeeper-server/src/test/java/org/apache/zookeeper/ClientReconnectTest.java
  7. 9 8
      zookeeper-server/src/test/java/org/apache/zookeeper/ClientRequestTimeoutTest.java
  8. 2 2
      zookeeper-server/src/test/java/org/apache/zookeeper/CustomHostProviderTest.java
  9. 7 3
      zookeeper-server/src/test/java/org/apache/zookeeper/GetAllChildrenNumberTest.java
  10. 12 8
      zookeeper-server/src/test/java/org/apache/zookeeper/GetEphemeralsTest.java
  11. 2 2
      zookeeper-server/src/test/java/org/apache/zookeeper/MultiOperationRecordTest.java
  12. 2 2
      zookeeper-server/src/test/java/org/apache/zookeeper/MultiResponseTest.java
  13. 26 42
      zookeeper-server/src/test/java/org/apache/zookeeper/PortAssignmentTest.java
  14. 41 33
      zookeeper-server/src/test/java/org/apache/zookeeper/RemoveWatchesCmdTest.java
  15. 246 210
      zookeeper-server/src/test/java/org/apache/zookeeper/RemoveWatchesTest.java
  16. 11 11
      zookeeper-server/src/test/java/org/apache/zookeeper/SaslAuthTest.java
  17. 17 12
      zookeeper-server/src/test/java/org/apache/zookeeper/ServerConfigTest.java
  18. 0 62
      zookeeper-server/src/test/java/org/apache/zookeeper/ZKParameterized.java
  19. 28 49
      zookeeper-server/src/test/java/org/apache/zookeeper/ZKTestCase.java
  20. 6 6
      zookeeper-server/src/test/java/org/apache/zookeeper/ZKUtilTest.java
  21. 42 44
      zookeeper-server/src/test/java/org/apache/zookeeper/ZooKeeperTest.java
  22. 2 2
      zookeeper-server/src/test/java/org/apache/zookeeper/audit/AuditEventTest.java
  23. 15 18
      zookeeper-server/src/test/java/org/apache/zookeeper/audit/Log4jAuditLoggerTest.java
  24. 7 7
      zookeeper-server/src/test/java/org/apache/zookeeper/audit/StandaloneServerAuditTest.java
  25. 2 2
      zookeeper-server/src/test/java/org/apache/zookeeper/cli/CommandFactoryTest.java
  26. 14 13
      zookeeper-server/src/test/java/org/apache/zookeeper/client/ZKClientConfigTest.java
  27. 43 43
      zookeeper-server/src/test/java/org/apache/zookeeper/common/AtomicFileWritingIdiomTest.java
  28. 35 13
      zookeeper-server/src/test/java/org/apache/zookeeper/common/BaseX509ParameterizedTestCase.java
  29. 9 9
      zookeeper-server/src/test/java/org/apache/zookeeper/common/FileChangeWatcherTest.java
  30. 7 4
      zookeeper-server/src/test/java/org/apache/zookeeper/common/FileKeyStoreLoaderBuilderProviderTest.java
  31. 98 60
      zookeeper-server/src/test/java/org/apache/zookeeper/common/JKSFileLoaderTest.java
  32. 20 11
      zookeeper-server/src/test/java/org/apache/zookeeper/common/KeyStoreFileTypeTest.java
  33. 20 11
      zookeeper-server/src/test/java/org/apache/zookeeper/common/NetUtilsTest.java
  34. 103 82
      zookeeper-server/src/test/java/org/apache/zookeeper/common/PEMFileLoaderTest.java
  35. 126 97
      zookeeper-server/src/test/java/org/apache/zookeeper/common/PKCS12FileLoaderTest.java
  36. 27 16
      zookeeper-server/src/test/java/org/apache/zookeeper/common/PathTrieTest.java
  37. 62 31
      zookeeper-server/src/test/java/org/apache/zookeeper/common/PathUtilsTest.java
  38. 2 2
      zookeeper-server/src/test/java/org/apache/zookeeper/common/TimeTest.java
  39. 401 218
      zookeeper-server/src/test/java/org/apache/zookeeper/common/X509UtilTest.java
  40. 10 13
      zookeeper-server/src/test/java/org/apache/zookeeper/common/ZKConfigTest.java
  41. 5 5
      zookeeper-server/src/test/java/org/apache/zookeeper/common/ZKHostnameVerifierTest.java
  42. 7 7
      zookeeper-server/src/test/java/org/apache/zookeeper/common/ZKTrustManagerTest.java
  43. 25 26
      zookeeper-server/src/test/java/org/apache/zookeeper/server/BlueThrottleTest.java
  44. 12 9
      zookeeper-server/src/test/java/org/apache/zookeeper/server/ByteBufferInputStreamTest.java
  45. 5 5
      zookeeper-server/src/test/java/org/apache/zookeeper/server/CRCTest.java
  46. 2 2
      zookeeper-server/src/test/java/org/apache/zookeeper/server/ConnectionMetricsTest.java
  47. 52 38
      zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateContainerTest.java
  48. 46 33
      zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateTTLTest.java
  49. 4 4
      zookeeper-server/src/test/java/org/apache/zookeeper/server/DataNodeTest.java
  50. 47 44
      zookeeper-server/src/test/java/org/apache/zookeeper/server/DataTreeTest.java
  51. 15 15
      zookeeper-server/src/test/java/org/apache/zookeeper/server/DatadirCleanupManagerTest.java
  52. 2 2
      zookeeper-server/src/test/java/org/apache/zookeeper/server/DeserializationPerfTest.java
  53. 13 9
      zookeeper-server/src/test/java/org/apache/zookeeper/server/Emulate353TTLTest.java
  54. 15 12
      zookeeper-server/src/test/java/org/apache/zookeeper/server/EphemeralTypeTest.java
  55. 7 7
      zookeeper-server/src/test/java/org/apache/zookeeper/server/FinalRequestProcessorTest.java
  56. 7 8
      zookeeper-server/src/test/java/org/apache/zookeeper/server/FollowerRequestProcessorTest.java
  57. 5 6
      zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapCountTest.java
  58. 3 3
      zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapshotTest.java
  59. 16 14
      zookeeper-server/src/test/java/org/apache/zookeeper/server/MultiOpSessionUpgradeTest.java
  60. 15 10
      zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnFactoryTest.java
  61. 11 9
      zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnTest.java
  62. 13 11
      zookeeper-server/src/test/java/org/apache/zookeeper/server/NettyServerCnxnFactoryTest.java
  63. 29 20
      zookeeper-server/src/test/java/org/apache/zookeeper/server/NettyServerCnxnTest.java
  64. 7 7
      zookeeper-server/src/test/java/org/apache/zookeeper/server/NodeHashMapImplTest.java
  65. 7 7
      zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorMetricsTest.java
  66. 19 19
      zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorTest.java
  67. 33 33
      zookeeper-server/src/test/java/org/apache/zookeeper/server/PurgeTxnTest.java
  68. 4 4
      zookeeper-server/src/test/java/org/apache/zookeeper/server/ReferenceCountedACLCacheTest.java
  69. 12 13
      zookeeper-server/src/test/java/org/apache/zookeeper/server/RequestThrottlerTest.java
  70. 1 1
      zookeeper-server/src/test/java/org/apache/zookeeper/server/SerializationPerfTest.java
  71. 28 42
      zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerIdTest.java
  72. 2 2
      zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerMetricsTest.java
  73. 4 4
      zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerStatsTest.java
  74. 18 15
      zookeeper-server/src/test/java/org/apache/zookeeper/server/SessionTrackerTest.java
  75. 7 7
      zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotDigestTest.java
  76. 2 2
      zookeeper-server/src/test/java/org/apache/zookeeper/server/ToStringTest.java
  77. 16 15
      zookeeper-server/src/test/java/org/apache/zookeeper/server/TxnLogDigestTest.java
  78. 2 2
      zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperCriticalThreadMetricsTest.java
  79. 8 8
      zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java
  80. 4 4
      zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerConfTest.java
  81. 1 1
      zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerCreationTest.java
  82. 57 67
      zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerMainTest.java
  83. 13 10
      zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerMaxCnxnsTest.java
  84. 24 18
      zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerStartupTest.java
  85. 6 6
      zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerTest.java
  86. 7 5
      zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperThreadTest.java
  87. 14 16
      zookeeper-server/src/test/java/org/apache/zookeeper/server/ZxidRolloverTest.java
  88. 4 4
      zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandResponseTest.java
  89. 12 22
      zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandsTest.java
  90. 20 26
      zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/JettyAdminServerTest.java
  91. 27 27
      zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxCounterSetTest.java
  92. 44 44
      zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterSetTest.java
  93. 24 24
      zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterTest.java
  94. 5 5
      zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/EmptySnapshotTest.java
  95. 22 38
      zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnLogTest.java
  96. 3 3
      zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogMetricsTest.java
  97. 52 45
      zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogTest.java
  98. 10 10
      zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/SnapStreamTest.java
  99. 24 19
      zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/TxnLogToolkitTest.java
  100. 2 2
      zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/BufferStatsTest.java

+ 18 - 0
pom.xml

@@ -430,6 +430,7 @@
     <audience-annotations.version>0.5.0</audience-annotations.version>
     <jmockit.version>1.48</jmockit.version>
     <junit.version>5.6.2</junit.version>
+    <junit-platform.version>1.6.2</junit-platform.version>
     <log4j.version>1.2.17</log4j.version>
     <mockito.version>2.27.0</mockito.version>
     <hamcrest.version>1.3</hamcrest.version>
@@ -554,11 +555,28 @@
         <artifactId>jmockit</artifactId>
         <version>${jmockit.version}</version>
       </dependency>
+      <dependency>
+        <groupId>org.junit.jupiter</groupId>
+        <artifactId>junit-jupiter-api</artifactId>
+        <version>${junit.version}</version>
+      </dependency>
       <dependency>
         <groupId>org.junit.jupiter</groupId>
         <artifactId>junit-jupiter-engine</artifactId>
         <version>${junit.version}</version>
       </dependency>
+      <dependency>
+        <groupId>org.junit.jupiter</groupId>
+        <artifactId>junit-jupiter-params</artifactId>
+        <version>${junit.version}</version>
+        <scope>test</scope>
+      </dependency>
+      <dependency>
+        <groupId>org.junit.platform</groupId>
+        <artifactId>junit-platform-runner</artifactId>
+        <version>${junit-platform.version}</version>
+        <scope>test</scope>
+      </dependency>
       <dependency>
         <groupId>org.junit.vintage</groupId>
         <artifactId>junit-vintage-engine</artifactId>

+ 20 - 0
zookeeper-server/pom.xml

@@ -156,6 +156,26 @@
       <artifactId>junit-vintage-engine</artifactId>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.junit.jupiter</groupId>
+      <artifactId>junit-jupiter-api</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.junit.jupiter</groupId>
+      <artifactId>junit-jupiter-engine</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.junit.jupiter</groupId>
+      <artifactId>junit-jupiter-params</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.junit.platform</groupId>
+      <artifactId>junit-platform-runner</artifactId>
+      <scope>test</scope>
+    </dependency>
     <dependency>
       <groupId>org.xerial.snappy</groupId>
       <artifactId>snappy-java</artifactId>

+ 5 - 5
zookeeper-server/src/test/java/org/apache/zookeeper/ClientCanonicalizeTest.java

@@ -18,13 +18,13 @@
 
 package org.apache.zookeeper;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 import java.io.IOException;
 import java.net.InetSocketAddress;
 import org.apache.zookeeper.client.ZKClientConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class ClientCanonicalizeTest extends ZKTestCase {
 
@@ -40,7 +40,7 @@ public class ClientCanonicalizeTest extends ZKTestCase {
 
         ZKClientConfig conf = new ZKClientConfig();
         String principal = SaslServerPrincipal.getServerPrincipal(addr, conf);
-        assertEquals("The computed principal does not appear to have been canonicalized", "zookeeper/zk1.apache.org", principal);
+        assertEquals("zookeeper/zk1.apache.org", principal, "The computed principal does not appear to have been canonicalized");
     }
 
     @Test
@@ -56,7 +56,7 @@ public class ClientCanonicalizeTest extends ZKTestCase {
         ZKClientConfig conf = new ZKClientConfig();
         conf.setProperty(ZKClientConfig.ZK_SASL_CLIENT_CANONICALIZE_HOSTNAME, "false");
         String principal = SaslServerPrincipal.getServerPrincipal(addr, conf);
-        assertEquals("The computed principal does appears to have been canonicalized incorrectly", "zookeeper/zookeeper.apache.org", principal);
+        assertEquals("zookeeper/zookeeper.apache.org", principal, "The computed principal does appears to have been canonicalized incorrectly");
     }
 
     @Test
@@ -71,7 +71,7 @@ public class ClientCanonicalizeTest extends ZKTestCase {
 
         ZKClientConfig conf = new ZKClientConfig();
         String principal = SaslServerPrincipal.getServerPrincipal(addr, conf);
-        assertEquals("The computed principal does appear to have falled back to the original host name", "zookeeper/zookeeper.apache.org", principal);
+        assertEquals("zookeeper/zookeeper.apache.org", principal, "The computed principal does appear to have falled back to the original host name");
     }
 
     @Test

+ 15 - 13
zookeeper-server/src/test/java/org/apache/zookeeper/ClientCnxnSocketFragilityTest.java

@@ -18,6 +18,9 @@
 
 package org.apache.zookeeper;
 
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.IOException;
 import java.net.InetSocketAddress;
 import java.util.Queue;
@@ -32,8 +35,7 @@ import org.apache.zookeeper.client.ZKClientConfig;
 import org.apache.zookeeper.data.Stat;
 import org.apache.zookeeper.server.quorum.QuorumPeerTestBase;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class ClientCnxnSocketFragilityTest extends QuorumPeerTestBase {
 
@@ -98,8 +100,8 @@ public class ClientCnxnSocketFragilityTest extends QuorumPeerTestBase {
 
         // Ensure server started
         for (int i = 0; i < SERVER_COUNT; i++) {
-            Assert.assertTrue("waiting for server " + i + " being up",
-                    ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
+            assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT),
+                    "waiting for server " + i + " being up");
         }
         String path = "/testClientCnxnSocketFragility";
         String data = "balabala";
@@ -109,8 +111,8 @@ public class ClientCnxnSocketFragilityTest extends QuorumPeerTestBase {
 
         // Let's see some successful operations
         zk.create(path, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
-        Assert.assertEquals(new String(zk.getData(path, false, new Stat())), data);
-        Assert.assertTrue(!watcher.isSessionExpired());
+        assertEquals(new String(zk.getData(path, false, new Stat())), data);
+        assertTrue(!watcher.isSessionExpired());
 
         // Let's make a broken operation
         socket.mute();
@@ -119,11 +121,11 @@ public class ClientCnxnSocketFragilityTest extends QuorumPeerTestBase {
             zk.getData(path, false, new Stat());
         } catch (KeeperException e) {
             catchKeeperException = true;
-            Assert.assertFalse(e instanceof KeeperException.SessionExpiredException);
+            assertFalse(e instanceof KeeperException.SessionExpiredException);
         }
         socket.unmute();
-        Assert.assertTrue(catchKeeperException);
-        Assert.assertTrue(!watcher.isSessionExpired());
+        assertTrue(catchKeeperException);
+        assertTrue(!watcher.isSessionExpired());
 
         GetDataRetryForeverBackgroundTask retryForeverGetData =
                 new GetDataRetryForeverBackgroundTask(zk, path);
@@ -143,8 +145,8 @@ public class ClientCnxnSocketFragilityTest extends QuorumPeerTestBase {
         TimeUnit.MILLISECONDS.sleep(3000);
 
         // Since we already close zookeeper, we expect that the zk should not be alive.
-        Assert.assertTrue(!zk.isAlive());
-        Assert.assertTrue(!watcher.isSessionExpired());
+        assertTrue(!zk.isAlive());
+        assertTrue(!watcher.isSessionExpired());
 
         retryForeverGetData.syncCloseTask();
         for (int i = 0; i < SERVER_COUNT; i++) {
@@ -324,7 +326,7 @@ public class ClientCnxnSocketFragilityTest extends QuorumPeerTestBase {
 
         @Override
         public void disconnect() {
-            Assert.assertTrue(closing);
+            assertTrue(closing);
             LOG.info("Attempt to disconnecting client for session: 0x{} {} {}", Long.toHexString(getSessionId()), closing, state);
             sendThread.close();
             ///////// Unsafe Region ////////
@@ -361,7 +363,7 @@ public class ClientCnxnSocketFragilityTest extends QuorumPeerTestBase {
             ClientCnxnSocket clientCnxnSocket,
             boolean canBeReadOnly
         ) throws IOException {
-            Assert.assertTrue(clientCnxnSocket instanceof FragileClientCnxnSocketNIO);
+            assertTrue(clientCnxnSocket instanceof FragileClientCnxnSocketNIO);
             socket = (FragileClientCnxnSocketNIO) clientCnxnSocket;
             ClientCnxnSocketFragilityTest.this.cnxn = new CustomClientCnxn(
                 chrootPath,

+ 7 - 7
zookeeper-server/src/test/java/org/apache/zookeeper/ClientCnxnSocketTest.java

@@ -18,24 +18,24 @@
 
 package org.apache.zookeeper;
 
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.IOException;
 import org.apache.zookeeper.client.ZKClientConfig;
 import org.apache.zookeeper.common.ZKConfig;
 import org.apache.zookeeper.test.TestByteBufAllocator;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class ClientCnxnSocketTest {
 
-    @Before
+    @BeforeEach
     public void setUp() {
         ClientCnxnSocketNetty.setTestAllocator(TestByteBufAllocator.getInstance());
     }
 
-    @After
+    @AfterEach
     public void tearDown() {
         ClientCnxnSocketNetty.clearTestAllocator();
         TestByteBufAllocator.checkForLeaks();

+ 2 - 2
zookeeper-server/src/test/java/org/apache/zookeeper/ClientReconnectTest.java

@@ -18,7 +18,7 @@
 
 package org.apache.zookeeper;
 
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.ArgumentMatchers.anyLong;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
@@ -29,7 +29,7 @@ import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import org.apache.zookeeper.client.HostProvider;
 import org.apache.zookeeper.client.ZKClientConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class ClientReconnectTest extends ZKTestCase {
 

+ 9 - 8
zookeeper-server/src/test/java/org/apache/zookeeper/ClientRequestTimeoutTest.java

@@ -19,9 +19,9 @@
 package org.apache.zookeeper;
 
 import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.IOException;
 import org.apache.zookeeper.ZooDefs.Ids;
 import org.apache.zookeeper.client.HostProvider;
@@ -29,7 +29,8 @@ import org.apache.zookeeper.client.ZKClientConfig;
 import org.apache.zookeeper.server.quorum.QuorumPeerTestBase;
 import org.apache.zookeeper.test.ClientBase;
 import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 public class ClientRequestTimeoutTest extends QuorumPeerTestBase {
 
@@ -37,7 +38,8 @@ public class ClientRequestTimeoutTest extends QuorumPeerTestBase {
     private boolean dropPacket = false;
     private int dropPacketType = ZooDefs.OpCode.create;
 
-    @Test(timeout = 120000)
+    @Test
+    @Timeout(value = 120)
     public void testClientRequestTimeout() throws Exception {
         int requestTimeOut = 15000;
         System.setProperty("zookeeper.request.timeout", Integer.toString(requestTimeOut));
@@ -61,9 +63,8 @@ public class ClientRequestTimeoutTest extends QuorumPeerTestBase {
 
         // ensure server started
         for (int i = 0; i < SERVER_COUNT; i++) {
-            assertTrue(
-                "waiting for server " + i + " being up",
-                ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
+            assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT),
+                "waiting for server " + i + " being up");
         }
 
         CountdownWatcher watch1 = new CountdownWatcher();

+ 2 - 2
zookeeper-server/src/test/java/org/apache/zookeeper/CustomHostProviderTest.java

@@ -18,14 +18,14 @@
 
 package org.apache.zookeeper;
 
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.IOException;
 import java.net.InetSocketAddress;
 import java.util.Collection;
 import java.util.concurrent.atomic.AtomicInteger;
 import org.apache.zookeeper.client.HostProvider;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class CustomHostProviderTest extends ZKTestCase {
 

+ 7 - 3
zookeeper-server/src/test/java/org/apache/zookeeper/GetAllChildrenNumberTest.java

@@ -18,14 +18,16 @@
 
 package org.apache.zookeeper;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.IOException;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import org.apache.zookeeper.ZooDefs.Ids;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class GetAllChildrenNumberTest extends ClientBase {
 
@@ -36,6 +38,7 @@ public class GetAllChildrenNumberTest extends ClientBase {
 
     private ZooKeeper zk;
 
+    @BeforeEach
     @Override
     public void setUp() throws Exception {
         super.setUp();
@@ -44,6 +47,7 @@ public class GetAllChildrenNumberTest extends ClientBase {
         generatePaths(PERSISTENT_CNT, EPHEMERAL_CNT);
     }
 
+    @AfterEach
     @Override
     public void tearDown() throws Exception {
         super.tearDown();

+ 12 - 8
zookeeper-server/src/test/java/org/apache/zookeeper/GetEphemeralsTest.java

@@ -18,9 +18,9 @@
 
 package org.apache.zookeeper;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
@@ -28,7 +28,9 @@ import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import org.apache.zookeeper.ZooDefs.Ids;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class GetEphemeralsTest extends ClientBase {
 
@@ -39,6 +41,7 @@ public class GetEphemeralsTest extends ClientBase {
     private String[] expected;
     private ZooKeeper zk;
 
+    @BeforeEach
     @Override
     public void setUp() throws Exception {
         super.setUp();
@@ -47,6 +50,7 @@ public class GetEphemeralsTest extends ClientBase {
         expected = generatePaths(PERSISTENT_CNT, EPHEMERAL_CNT);
     }
 
+    @AfterEach
     @Override
     public void tearDown() throws Exception {
         super.tearDown();
@@ -57,10 +61,10 @@ public class GetEphemeralsTest extends ClientBase {
     @Test
     public void testGetEphemeralsSync() throws KeeperException, InterruptedException {
         List<String> actual = zk.getEphemerals();
-        assertEquals("Expected ephemeral count for allPaths", actual.size(), expected.length);
+        assertEquals(actual.size(), expected.length, "Expected ephemeral count for allPaths");
         for (int i = 0; i < expected.length; i++) {
             String path = expected[i];
-            assertTrue(String.format("Path=%s exists in get All Ephemerals list ", path), actual.contains(path));
+            assertTrue(actual.contains(path), String.format("Path=%s exists in get All Ephemerals list ", path));
         }
     }
 
@@ -68,10 +72,10 @@ public class GetEphemeralsTest extends ClientBase {
     public void testGetEphemeralsSyncByPath() throws KeeperException, InterruptedException {
         final String prefixPath = BASE + 0;
         List<String> actual = zk.getEphemerals(prefixPath);
-        assertEquals("Expected ephemeral count for allPaths", actual.size(), EPHEMERAL_CNT);
+        assertEquals(actual.size(), EPHEMERAL_CNT, "Expected ephemeral count for allPaths");
         for (int i = 0; i < EPHEMERAL_CNT; i++) {
             String path = expected[i];
-            assertTrue(String.format("Path=%s exists in getEphemerals(%s) list ", path, prefixPath), actual.contains(path));
+            assertTrue(actual.contains(path), String.format("Path=%s exists in getEphemerals(%s) list ", path, prefixPath));
         }
     }
 

+ 2 - 2
zookeeper-server/src/test/java/org/apache/zookeeper/MultiOperationRecordTest.java

@@ -18,14 +18,14 @@
 
 package org.apache.zookeeper;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.nio.ByteBuffer;
 import org.apache.jute.BinaryInputArchive;
 import org.apache.jute.BinaryOutputArchive;
 import org.apache.zookeeper.server.ByteBufferInputStream;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class MultiOperationRecordTest extends ZKTestCase {
 

+ 2 - 2
zookeeper-server/src/test/java/org/apache/zookeeper/MultiResponseTest.java

@@ -17,7 +17,7 @@
 
 package org.apache.zookeeper;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.nio.ByteBuffer;
@@ -25,7 +25,7 @@ import org.apache.jute.BinaryInputArchive;
 import org.apache.jute.BinaryOutputArchive;
 import org.apache.zookeeper.data.Stat;
 import org.apache.zookeeper.server.ByteBufferInputStream;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class MultiResponseTest extends ZKTestCase {
 

+ 26 - 42
zookeeper-server/src/test/java/org/apache/zookeeper/PortAssignmentTest.java

@@ -18,56 +18,40 @@
 
 package org.apache.zookeeper;
 
-import static org.junit.Assert.assertEquals;
-import java.util.Arrays;
-import java.util.Collection;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import java.util.stream.Stream;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
 
-@RunWith(Parameterized.class)
-@Parameterized.UseParametersRunnerFactory(ZKParameterized.RunnerFactory.class)
 public class PortAssignmentTest {
 
-    private final String strProcessCount;
-    private final String cmdLine;
-    private final int expectedMinimumPort;
-    private final int expectedMaximumPort;
-
-    @Parameters
-    public static Collection<Object[]> data() {
-        return Arrays.asList(
-            new Object[]{"8", "threadid=1", 11221, 13913},
-            new Object[]{"8", "threadid=2", 13914, 16606},
-            new Object[]{"8", "threadid=3", 16607, 19299},
-            new Object[]{"8", "threadid=4", 19300, 21992},
-            new Object[]{"8", "threadid=5", 21993, 24685},
-            new Object[]{"8", "threadid=6", 24686, 27378},
-            new Object[]{"8", "threadid=7", 27379, 30071},
-            new Object[]{"8", "threadid=8", 30072, 32764},
-            new Object[]{"1", "threadid=1", 11221, 32767},
-            new Object[]{"2", "threadid=1", 11221, 21993},
-            new Object[]{"2", "threadid=2", 21994, 32766},
-            new Object[]{null, null, 11221, 32767},
-            new Object[]{"", "", 11221, 32767});
-    }
-
-    public PortAssignmentTest(String strProcessCount, String cmdLine, int expectedMinimumPort, int expectedMaximumPort) {
-        this.strProcessCount = strProcessCount;
-        this.cmdLine = cmdLine;
-        this.expectedMinimumPort = expectedMinimumPort;
-        this.expectedMaximumPort = expectedMaximumPort;
+    public static Stream<Arguments> data() throws Exception {
+        return Stream.of(
+                Arguments.of("8", "threadid=1", 11221, 13913),
+                Arguments.of("8", "threadid=2", 13914, 16606),
+                Arguments.of("8", "threadid=3", 16607, 19299),
+                Arguments.of("8", "threadid=4", 19300, 21992),
+                Arguments.of("8", "threadid=5", 21993, 24685),
+                Arguments.of("8", "threadid=6", 24686, 27378),
+                Arguments.of("8", "threadid=7", 27379, 30071),
+                Arguments.of("8", "threadid=8", 30072, 32764),
+                Arguments.of("1", "threadid=1", 11221, 32767),
+                Arguments.of("2", "threadid=1", 11221, 21993),
+                Arguments.of("2", "threadid=2", 21994, 32766),
+                Arguments.of(null, null, 11221, 32767),
+                Arguments.of("", "", 11221, 32767));
     }
 
-    @Test
-    public void testSetupPortRange() {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testSetupPortRange(String strProcessCount, String cmdLine, int expectedMinimumPort, int expectedMaximumPort) {
         PortAssignment.PortRange portRange = PortAssignment.setupPortRange(strProcessCount, cmdLine);
-        assertEquals(buildAssertionMessage("minimum"), expectedMinimumPort, portRange.getMinimum());
-        assertEquals(buildAssertionMessage("maximum"), expectedMaximumPort, portRange.getMaximum());
+        assertEquals(expectedMinimumPort, portRange.getMinimum(), buildAssertionMessage("minimum", strProcessCount, cmdLine));
+        assertEquals(expectedMaximumPort, portRange.getMaximum(), buildAssertionMessage("maximum", strProcessCount, cmdLine));
     }
 
-    private String buildAssertionMessage(String checkType) {
+    private String buildAssertionMessage(String checkType, String strProcessCount, String cmdLine) {
         return String.format("strProcessCount = %s, cmdLine = %s, checking %s", strProcessCount, cmdLine, checkType);
     }
 

+ 41 - 33
zookeeper-server/src/test/java/org/apache/zookeeper/RemoveWatchesCmdTest.java

@@ -18,8 +18,8 @@
 
 package org.apache.zookeeper;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -29,7 +29,10 @@ import java.util.concurrent.TimeUnit;
 import org.apache.zookeeper.Watcher.Event.EventType;
 import org.apache.zookeeper.ZooDefs.Ids;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -42,6 +45,7 @@ public class RemoveWatchesCmdTest extends ClientBase {
     private ZooKeeper zk;
     private ZooKeeperMain zkMain;
 
+    @BeforeEach
     @Override
     public void setUp() throws Exception {
         super.setUp();
@@ -49,6 +53,7 @@ public class RemoveWatchesCmdTest extends ClientBase {
         zkMain = new ZooKeeperMain(zk);
     }
 
+    @AfterEach
     @Override
     public void tearDown() throws Exception {
         if (zk != null) {
@@ -62,7 +67,8 @@ public class RemoveWatchesCmdTest extends ClientBase {
      * removewatches command will use default options - WatcherType.ANY and
      * local=false
      */
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testRemoveWatchesWithNoPassedOptions() throws Exception {
         List<EventType> expectedEvents = new ArrayList<>();
         expectedEvents.add(EventType.ChildWatchRemoved);
@@ -83,19 +89,20 @@ public class RemoveWatchesCmdTest extends ClientBase {
         String cmdstring = "removewatches /testnode1";
         LOG.info("Remove watchers using shell command : {}", cmdstring);
         zkMain.cl.parseCommand(cmdstring);
-        assertTrue("Removewatches cmd fails to remove child watches", zkMain.processZKCmd(zkMain.cl));
+        assertTrue(zkMain.processZKCmd(zkMain.cl), "Removewatches cmd fails to remove child watches");
         LOG.info("Waiting for the DataWatchRemoved event");
         myWatcher.matches();
 
         // verifying that other path child watches are not affected
-        assertTrue("Failed to find child watches for the path testnode2", zk.getChildWatches().contains("/testnode2"));
-        assertTrue("Failed to find data watches for the path testnode2", zk.getDataWatches().contains("/testnode2"));
+        assertTrue(zk.getChildWatches().contains("/testnode2"), "Failed to find child watches for the path testnode2");
+        assertTrue(zk.getDataWatches().contains("/testnode2"), "Failed to find data watches for the path testnode2");
     }
 
     /**
      * Test verifies deletion of NodeDataChanged watches
      */
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testRemoveNodeDataChangedWatches() throws Exception {
         LOG.info("Adding data watcher using getData()");
         List<EventType> expectedEvents = new ArrayList<>();
@@ -108,19 +115,20 @@ public class RemoveWatchesCmdTest extends ClientBase {
         String cmdstring = "removewatches /testnode1 -d";
         LOG.info("Remove watchers using shell command : {}", cmdstring);
         zkMain.cl.parseCommand(cmdstring);
-        assertTrue("Removewatches cmd fails to remove data watches", zkMain.processZKCmd(zkMain.cl));
+        assertTrue(zkMain.processZKCmd(zkMain.cl), "Removewatches cmd fails to remove data watches");
 
         LOG.info("Waiting for the DataWatchRemoved event");
         myWatcher.matches();
 
         // verifying that other path data watches are removed
-        assertEquals("Data watches are not removed : " + zk.getDataWatches(), 0, zk.getDataWatches().size());
+        assertEquals(0, zk.getDataWatches().size(), "Data watches are not removed : " + zk.getDataWatches());
     }
 
     /**
      * Test verifies deletion of NodeCreated data watches
      */
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testRemoveNodeCreatedWatches() throws Exception {
         List<EventType> expectedEvents = new ArrayList<>();
         expectedEvents.add(EventType.DataWatchRemoved);
@@ -134,27 +142,25 @@ public class RemoveWatchesCmdTest extends ClientBase {
         String cmdstring1 = "removewatches /testnode1 -d";
         LOG.info("Remove watchers using shell command : {}", cmdstring1);
         zkMain.cl.parseCommand(cmdstring1);
-        assertTrue("Removewatches cmd fails to remove pre-create watches", zkMain.processZKCmd(zkMain.cl));
+        assertTrue(zkMain.processZKCmd(zkMain.cl), "Removewatches cmd fails to remove pre-create watches");
         myWatcher1.matches();
-        assertEquals("Failed to remove pre-create watches :"
-                                    + zk.getExistWatches(), 1, zk.getExistWatches().size());
-        assertTrue("Failed to remove pre-create watches :"
-                                  + zk.getExistWatches(), zk.getExistWatches().contains("/testnode1/testnode2"));
+        assertEquals(1, zk.getExistWatches().size(), "Failed to remove pre-create watches :" + zk.getExistWatches());
+        assertTrue(zk.getExistWatches().contains("/testnode1/testnode2"), "Failed to remove pre-create watches :" + zk.getExistWatches());
 
         String cmdstring2 = "removewatches /testnode1/testnode2 -d";
         LOG.info("Remove watchers using shell command : {}", cmdstring2);
         zkMain.cl.parseCommand(cmdstring2);
-        assertTrue("Removewatches cmd fails to remove data watches", zkMain.processZKCmd(zkMain.cl));
+        assertTrue(zkMain.processZKCmd(zkMain.cl), "Removewatches cmd fails to remove data watches");
 
         myWatcher2.matches();
-        assertEquals("Failed to remove pre-create watches : "
-                                    + zk.getExistWatches(), 0, zk.getExistWatches().size());
+        assertEquals(0, zk.getExistWatches().size(), "Failed to remove pre-create watches : " + zk.getExistWatches());
     }
 
     /**
      * Test verifies deletion of NodeChildrenChanged watches
      */
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testRemoveNodeChildrenChangedWatches() throws Exception {
         List<EventType> expectedEvents = new ArrayList<>();
         expectedEvents.add(EventType.ChildWatchRemoved);
@@ -167,15 +173,16 @@ public class RemoveWatchesCmdTest extends ClientBase {
         String cmdstring = "removewatches /testnode1 -c";
         LOG.info("Remove watchers using shell command : {}", cmdstring);
         zkMain.cl.parseCommand(cmdstring);
-        assertTrue("Removewatches cmd fails to remove child watches", zkMain.processZKCmd(zkMain.cl));
+        assertTrue(zkMain.processZKCmd(zkMain.cl), "Removewatches cmd fails to remove child watches");
         myWatcher.matches();
-        assertEquals("Failed to remove child watches : " + zk.getChildWatches(), 0, zk.getChildWatches().size());
+        assertEquals(0, zk.getChildWatches().size(), "Failed to remove child watches : " + zk.getChildWatches());
     }
 
     /**
      * Test verifies deletion of NodeDeleted watches
      */
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testRemoveNodeDeletedWatches() throws Exception {
         LOG.info("Adding NodeDeleted watcher");
         List<EventType> expectedEvents = new ArrayList<>();
@@ -191,13 +198,12 @@ public class RemoveWatchesCmdTest extends ClientBase {
         String cmdstring = "removewatches /testnode1 -c";
         LOG.info("Remove watchers using shell command : {}", cmdstring);
         zkMain.cl.parseCommand(cmdstring);
-        assertTrue("Removewatches cmd fails to remove child watches", zkMain.processZKCmd(zkMain.cl));
+        assertTrue(zkMain.processZKCmd(zkMain.cl), "Removewatches cmd fails to remove child watches");
         LOG.info("Waiting for the ChildWatchRemoved event");
         myWatcher.matches();
-        assertEquals("Failed to remove child watches : " + zk.getChildWatches(), 1, zk.getChildWatches().size());
+        assertEquals(1, zk.getChildWatches().size(), "Failed to remove child watches : " + zk.getChildWatches());
 
-        assertTrue("Failed to remove child watches :"
-                                  + zk.getChildWatches(), zk.getChildWatches().contains("/testnode1/testnode2"));
+        assertTrue(zk.getChildWatches().contains("/testnode1/testnode2"), "Failed to remove child watches :" + zk.getChildWatches());
 
         // verify node delete watcher
         zk.delete("/testnode1/testnode2", -1);
@@ -207,7 +213,8 @@ public class RemoveWatchesCmdTest extends ClientBase {
     /**
      * Test verifies deletion of any watches
      */
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testRemoveAnyWatches() throws Exception {
         verifyRemoveAnyWatches(false);
     }
@@ -216,7 +223,8 @@ public class RemoveWatchesCmdTest extends ClientBase {
      * Test verifies deletion of watches locally when there is no server
      * connection
      */
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testRemoveWatchesLocallyWhenNoServerConnection() throws Exception {
         verifyRemoveAnyWatches(true);
     }
@@ -259,12 +267,12 @@ public class RemoveWatchesCmdTest extends ClientBase {
 
         LOG.info("Remove watchers using shell command : {}", cmdstring);
         zkMain.cl.parseCommand(cmdstring);
-        assertTrue("Removewatches cmd fails to remove child/data watches", zkMain.processZKCmd(zkMain.cl));
+        assertTrue(zkMain.processZKCmd(zkMain.cl), "Removewatches cmd fails to remove child/data watches");
         LOG.info("Waiting for the WatchRemoved events");
         watcherLatch.await(10, TimeUnit.SECONDS);
-        assertEquals("Didn't receives WatchRemoved events!", 1, pathVsEvent.size());
-        assertTrue("Didn't receives DataWatchRemoved!", pathVsEvent.get("/testnode1").contains(EventType.DataWatchRemoved));
-        assertTrue("Didn't receives ChildWatchRemoved!", pathVsEvent.get("/testnode1").contains(EventType.ChildWatchRemoved));
+        assertEquals(1, pathVsEvent.size(), "Didn't receives WatchRemoved events!");
+        assertTrue(pathVsEvent.get("/testnode1").contains(EventType.DataWatchRemoved), "Didn't receives DataWatchRemoved!");
+        assertTrue(pathVsEvent.get("/testnode1").contains(EventType.ChildWatchRemoved), "Didn't receives ChildWatchRemoved!");
     }
 
     private static class MyWatcher implements Watcher {

+ 246 - 210
zookeeper-server/src/test/java/org/apache/zookeeper/RemoveWatchesTest.java

@@ -19,19 +19,17 @@
 package org.apache.zookeeper;
 
 import static org.hamcrest.CoreMatchers.is;
-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;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.spy;
 import java.io.IOException;
 import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
@@ -46,24 +44,24 @@ import org.apache.zookeeper.Watcher.WatcherType;
 import org.apache.zookeeper.ZooDefs.Ids;
 import org.apache.zookeeper.server.ServerCnxn;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
  * Verifies removing watches using ZooKeeper client apis
  */
-@RunWith(Parameterized.class)
-@Parameterized.UseParametersRunnerFactory(ZKParameterized.RunnerFactory.class)
 public class RemoveWatchesTest extends ClientBase {
 
     private static final Logger LOG = LoggerFactory.getLogger(RemoveWatchesTest.class);
     private ZooKeeper zk1 = null;
     private ZooKeeper zk2 = null;
 
+    @BeforeEach
     @Override
     public void setUp() throws Exception {
         super.setUp();
@@ -71,6 +69,7 @@ public class RemoveWatchesTest extends ClientBase {
         zk2 = createClient();
     }
 
+    @AfterEach
     @Override
     public void tearDown() throws Exception {
         if (zk1 != null) {
@@ -82,29 +81,19 @@ public class RemoveWatchesTest extends ClientBase {
         super.tearDown();
     }
 
-    private final boolean useAsync;
-
-    public RemoveWatchesTest(boolean useAsync) {
-        this.useAsync = useAsync;
-    }
-
-    @Parameters
-    public static Collection<Object[]> configs() {
-        return Arrays.asList(new Object[][]{{false}, {true}});
-    }
-
     private void removeWatches(
         ZooKeeper zk,
         String path,
         Watcher watcher,
         WatcherType watcherType,
         boolean local,
-        KeeperException.Code rc) throws InterruptedException, KeeperException {
+        KeeperException.Code rc,
+        boolean useAsync) throws InterruptedException, KeeperException {
         LOG.info("Sending removeWatches req using zk {} path: {} type: {} watcher: {} ", zk, path, watcherType, watcher);
         if (useAsync) {
             MyCallback c1 = new MyCallback(rc.intValue(), path);
             zk.removeWatches(path, watcher, watcherType, local, c1, null);
-            assertTrue("Didn't succeeds removeWatch operation", c1.matches());
+            assertTrue(c1.matches(), "Didn't succeeds removeWatch operation");
             if (KeeperException.Code.OK.intValue() != c1.rc) {
                 KeeperException ke = KeeperException.create(KeeperException.Code.get(c1.rc));
                 throw ke;
@@ -119,12 +108,13 @@ public class RemoveWatchesTest extends ClientBase {
         String path,
         WatcherType watcherType,
         boolean local,
-        KeeperException.Code rc) throws InterruptedException, KeeperException {
+        KeeperException.Code rc,
+        boolean useAsync) throws InterruptedException, KeeperException {
         LOG.info("Sending removeWatches req using zk {} path: {} type: {} ", zk, path, watcherType);
         if (useAsync) {
             MyCallback c1 = new MyCallback(rc.intValue(), path);
             zk.removeAllWatches(path, watcherType, local, c1, null);
-            assertTrue("Didn't succeeds removeWatch operation", c1.matches());
+            assertTrue(c1.matches(), "Didn't succeeds removeWatch operation");
             if (KeeperException.Code.OK.intValue() != c1.rc) {
                 KeeperException ke = KeeperException.create(KeeperException.Code.get(c1.rc));
                 throw ke;
@@ -137,21 +127,23 @@ public class RemoveWatchesTest extends ClientBase {
     /**
      * Test verifies removal of single watcher when there is server connection
      */
-    @Test(timeout = 90000)
-    public void testRemoveSingleWatcher() throws Exception {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testRemoveSingleWatcher(boolean useAsync) throws Exception {
         zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
         zk1.create("/node2", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
         MyWatcher w1 = new MyWatcher("/node1", 1);
         LOG.info("Adding data watcher {} on path {}", w1, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+        assertNotNull(zk2.exists("/node1", w1), "Didn't set data watches");
         MyWatcher w2 = new MyWatcher("/node2", 1);
         LOG.info("Adding data watcher {} on path {}", w2, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node2", w2));
-        removeWatches(zk2, "/node1", w1, WatcherType.Data, false, Code.OK);
-        assertEquals("Didn't find data watcher", 1, zk2.getDataWatches().size());
-        assertEquals("Didn't find data watcher", "/node2", zk2.getDataWatches().get(0));
-        removeWatches(zk2, "/node2", w2, WatcherType.Any, false, Code.OK);
-        assertTrue("Didn't remove data watcher", w2.matches());
+        assertNotNull(zk2.exists("/node2", w2), "Didn't set data watches");
+        removeWatches(zk2, "/node1", w1, WatcherType.Data, false, Code.OK, useAsync);
+        assertEquals(1, zk2.getDataWatches().size(), "Didn't find data watcher");
+        assertEquals("/node2", zk2.getDataWatches().get(0), "Didn't find data watcher");
+        removeWatches(zk2, "/node2", w2, WatcherType.Any, false, Code.OK, useAsync);
+        assertTrue(w2.matches(), "Didn't remove data watcher");
         // closing session should remove ephemeral nodes and trigger data
         // watches if any
         if (zk1 != null) {
@@ -160,28 +152,30 @@ public class RemoveWatchesTest extends ClientBase {
         }
 
         List<EventType> events = w1.getEventsAfterWatchRemoval();
-        assertFalse("Shouldn't get NodeDeletedEvent after watch removal", events.contains(EventType.NodeDeleted));
-        assertEquals("Shouldn't get NodeDeletedEvent after watch removal", 0, events.size());
+        assertFalse(events.contains(EventType.NodeDeleted), "Shouldn't get NodeDeletedEvent after watch removal");
+        assertEquals(0, events.size(), "Shouldn't get NodeDeletedEvent after watch removal");
     }
 
     /**
      * Test verifies removal of multiple data watchers when there is server
      * connection
      */
-    @Test(timeout = 90000)
-    public void testMultipleDataWatchers() throws IOException, InterruptedException, KeeperException {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testMultipleDataWatchers(boolean useAsync) throws IOException, InterruptedException, KeeperException {
         zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
         MyWatcher w1 = new MyWatcher("/node1", 1);
         LOG.info("Adding data watcher {} on path {}", w1, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+        assertNotNull(zk2.exists("/node1", w1), "Didn't set data watches");
         MyWatcher w2 = new MyWatcher("/node1", 1);
         LOG.info("Adding data watcher {} on path {}", w2, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w2));
-        removeWatches(zk2, "/node1", w2, WatcherType.Data, false, Code.OK);
-        assertEquals("Didn't find data watcher", 1, zk2.getDataWatches().size());
-        assertEquals("Didn't find data watcher", "/node1", zk2.getDataWatches().get(0));
-        removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK);
-        assertTrue("Didn't remove data watcher", w2.matches());
+        assertNotNull(zk2.exists("/node1", w2), "Didn't set data watches");
+        removeWatches(zk2, "/node1", w2, WatcherType.Data, false, Code.OK, useAsync);
+        assertEquals(1, zk2.getDataWatches().size(), "Didn't find data watcher");
+        assertEquals("/node1", zk2.getDataWatches().get(0), "Didn't find data watcher");
+        removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK, useAsync);
+        assertTrue(w2.matches(), "Didn't remove data watcher");
         // closing session should remove ephemeral nodes and trigger data
         // watches if any
         if (zk1 != null) {
@@ -190,15 +184,17 @@ public class RemoveWatchesTest extends ClientBase {
         }
 
         List<EventType> events = w2.getEventsAfterWatchRemoval();
-        assertEquals("Shouldn't get NodeDeletedEvent after watch removal", 0, events.size());
+        assertEquals(0, events.size(), "Shouldn't get NodeDeletedEvent after watch removal");
     }
 
     /**
      * Test verifies removal of multiple child watchers when there is server
      * connection
      */
-    @Test(timeout = 90000)
-    public void testMultipleChildWatchers() throws IOException, InterruptedException, KeeperException {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testMultipleChildWatchers(boolean useAsync) throws IOException, InterruptedException, KeeperException {
         zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         MyWatcher w1 = new MyWatcher("/node1", 1);
         LOG.info("Adding child watcher {} on path {}", w1, "/node1");
@@ -206,11 +202,11 @@ public class RemoveWatchesTest extends ClientBase {
         MyWatcher w2 = new MyWatcher("/node1", 1);
         LOG.info("Adding child watcher {} on path {}", w2, "/node1");
         zk2.getChildren("/node1", w2);
-        removeWatches(zk2, "/node1", w2, WatcherType.Children, false, Code.OK);
-        assertTrue("Didn't remove child watcher", w2.matches());
-        assertEquals("Didn't find child watcher", 1, zk2.getChildWatches().size());
-        removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK);
-        assertTrue("Didn't remove child watcher", w1.matches());
+        removeWatches(zk2, "/node1", w2, WatcherType.Children, false, Code.OK, useAsync);
+        assertTrue(w2.matches(), "Didn't remove child watcher");
+        assertEquals(1, zk2.getChildWatches().size(), "Didn't find child watcher");
+        removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK, useAsync);
+        assertTrue(w1.matches(), "Didn't remove child watcher");
         // create child to see NodeChildren notification
         zk1.create("/node1/node2", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         // waiting for child watchers to be notified
@@ -224,55 +220,59 @@ public class RemoveWatchesTest extends ClientBase {
         }
         // watcher2
         List<EventType> events = w2.getEventsAfterWatchRemoval();
-        assertEquals("Shouldn't get NodeChildrenChanged event", 0, events.size());
+        assertEquals(0, events.size(), "Shouldn't get NodeChildrenChanged event");
     }
 
     /**
      * Test verifies null watcher with WatcherType.Any - remove all the watchers
      * data, child, exists
      */
-    @Test(timeout = 90000)
-    public void testRemoveAllWatchers() throws IOException, InterruptedException, KeeperException {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testRemoveAllWatchers(boolean useAsync) throws IOException, InterruptedException, KeeperException {
         zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         MyWatcher w1 = new MyWatcher("/node1", 2);
         MyWatcher w2 = new MyWatcher("/node1", 2);
         LOG.info("Adding data watcher {} on path {}", w1, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+        assertNotNull(zk2.exists("/node1", w1), "Didn't set data watches");
         LOG.info("Adding data watcher {} on path {}", w2, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w2));
+        assertNotNull(zk2.exists("/node1", w2), "Didn't set data watches");
         LOG.info("Adding child watcher {} on path {}", w1, "/node1");
         zk2.getChildren("/node1", w1);
         LOG.info("Adding child watcher {} on path {}", w2, "/node1");
         zk2.getChildren("/node1", w2);
-        removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK);
-        removeWatches(zk2, "/node1", w2, WatcherType.Any, false, Code.OK);
+        removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK, useAsync);
+        removeWatches(zk2, "/node1", w2, WatcherType.Any, false, Code.OK, useAsync);
         zk1.create("/node1/child", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
-        assertTrue("Didn't remove data watcher", w1.matches());
-        assertTrue("Didn't remove child watcher", w2.matches());
+        assertTrue(w1.matches(), "Didn't remove data watcher");
+        assertTrue(w2.matches(), "Didn't remove child watcher");
     }
 
     /**
      * Test verifies null watcher with WatcherType.Data - remove all data
      * watchers. Child watchers shouldn't be removed
      */
-    @Test(timeout = 90000)
-    public void testRemoveAllDataWatchers() throws IOException, InterruptedException, KeeperException {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testRemoveAllDataWatchers(boolean useAsync) throws IOException, InterruptedException, KeeperException {
         zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         MyWatcher w1 = new MyWatcher("/node1", 1);
         MyWatcher w2 = new MyWatcher("/node1", 1);
         LOG.info("Adding data watcher {} on path {}", w1, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+        assertNotNull(zk2.exists("/node1", w1), "Didn't set data watches");
         LOG.info("Adding data watcher {} on path {}", w2, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w2));
+        assertNotNull(zk2.exists("/node1", w2), "Didn't set data watches");
         LOG.info("Adding child watcher {} on path {}", w1, "/node1");
         zk2.getChildren("/node1", w1);
         LOG.info("Adding child watcher {} on path {}", w2, "/node1");
         zk2.getChildren("/node1", w2);
-        removeWatches(zk2, "/node1", w1, WatcherType.Data, false, Code.OK);
-        removeWatches(zk2, "/node1", w2, WatcherType.Data, false, Code.OK);
+        removeWatches(zk2, "/node1", w1, WatcherType.Data, false, Code.OK, useAsync);
+        removeWatches(zk2, "/node1", w2, WatcherType.Data, false, Code.OK, useAsync);
         zk1.create("/node1/child", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
-        assertTrue("Didn't remove data watcher", w1.matches());
-        assertTrue("Didn't remove data watcher", w2.matches());
+        assertTrue(w1.matches(), "Didn't remove data watcher");
+        assertTrue(w2.matches(), "Didn't remove data watcher");
         // waiting for child watchers to be notified
         int count = 10;
         while (count > 0) {
@@ -284,36 +284,38 @@ public class RemoveWatchesTest extends ClientBase {
         }
         // watcher1
         List<EventType> events = w1.getEventsAfterWatchRemoval();
-        assertEquals("Didn't get NodeChildrenChanged event", 1, events.size());
-        assertTrue("Didn't get NodeChildrenChanged event", events.contains(EventType.NodeChildrenChanged));
+        assertEquals(1, events.size(), "Didn't get NodeChildrenChanged event");
+        assertTrue(events.contains(EventType.NodeChildrenChanged), "Didn't get NodeChildrenChanged event");
         // watcher2
         events = w2.getEventsAfterWatchRemoval();
-        assertEquals("Didn't get NodeChildrenChanged event", 1, events.size());
-        assertTrue("Didn't get NodeChildrenChanged event", events.contains(EventType.NodeChildrenChanged));
+        assertEquals(1, events.size(), "Didn't get NodeChildrenChanged event");
+        assertTrue(events.contains(EventType.NodeChildrenChanged), "Didn't get NodeChildrenChanged event");
     }
 
     /**
      * Test verifies null watcher with WatcherType.Children - remove all child
      * watchers. Data watchers shouldn't be removed
      */
-    @Test(timeout = 90000)
-    public void testRemoveAllChildWatchers() throws IOException, InterruptedException, KeeperException {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testRemoveAllChildWatchers(boolean useAsync) throws IOException, InterruptedException, KeeperException {
         zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         MyWatcher w1 = new MyWatcher("/node1", 1);
         MyWatcher w2 = new MyWatcher("/node1", 1);
         LOG.info("Adding data watcher {} on path {}", w1, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+        assertNotNull(zk2.exists("/node1", w1), "Didn't set data watches");
         LOG.info("Adding data watcher {} on path {}", w2, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w2));
+        assertNotNull(zk2.exists("/node1", w2), "Didn't set data watches");
         LOG.info("Adding child watcher {} on path {}", w1, "/node1");
         zk2.getChildren("/node1", w1);
         LOG.info("Adding child watcher {} on path {}", w2, "/node1");
         zk2.getChildren("/node1", w2);
-        removeWatches(zk2, "/node1", w1, WatcherType.Children, false, Code.OK);
-        removeWatches(zk2, "/node1", w2, WatcherType.Children, false, Code.OK);
+        removeWatches(zk2, "/node1", w1, WatcherType.Children, false, Code.OK, useAsync);
+        removeWatches(zk2, "/node1", w2, WatcherType.Children, false, Code.OK, useAsync);
         zk1.setData("/node1", "test".getBytes(), -1);
-        assertTrue("Didn't remove child watcher", w1.matches());
-        assertTrue("Didn't remove child watcher", w2.matches());
+        assertTrue(w1.matches(), "Didn't remove child watcher");
+        assertTrue(w2.matches(), "Didn't remove child watcher");
         // waiting for child watchers to be notified
         int count = 10;
         while (count > 0) {
@@ -325,26 +327,28 @@ public class RemoveWatchesTest extends ClientBase {
         }
         // watcher1
         List<EventType> events = w1.getEventsAfterWatchRemoval();
-        assertEquals("Didn't get NodeDataChanged event", 1, events.size());
-        assertTrue("Didn't get NodeDataChanged event", events.contains(EventType.NodeDataChanged));
+        assertEquals(1, events.size(), "Didn't get NodeDataChanged event");
+        assertTrue(events.contains(EventType.NodeDataChanged), "Didn't get NodeDataChanged event");
         // watcher2
         events = w2.getEventsAfterWatchRemoval();
-        assertEquals("Didn't get NodeDataChanged event", 1, events.size());
-        assertTrue("Didn't get NodeDataChanged event", events.contains(EventType.NodeDataChanged));
+        assertEquals(1, events.size(), "Didn't get NodeDataChanged event");
+        assertTrue(events.contains(EventType.NodeDataChanged), "Didn't get NodeDataChanged event");
     }
 
     /**
      * Test verifies given watcher doesn't exists!
      */
-    @Test(timeout = 90000)
-    public void testNoWatcherException() throws IOException, InterruptedException, KeeperException {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testNoWatcherException(boolean useAsync) throws IOException, InterruptedException, KeeperException {
         zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         MyWatcher w1 = new MyWatcher("/node1", 2);
         MyWatcher w2 = new MyWatcher("/node1", 2);
         LOG.info("Adding data watcher {} on path {}", w1, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+        assertNotNull(zk2.exists("/node1", w1), "Didn't set data watches");
         LOG.info("Adding data watcher {} on path {}", w2, "/node1");
-        assertNull("Didn't set data watches", zk2.exists("/node2", w2));
+        assertNull(zk2.exists("/node2", w2), "Didn't set data watches");
         LOG.info("Adding child watcher {} on path {}", w1, "/node1");
         zk2.getChildren("/node1", w1);
         LOG.info("Adding child watcher {} on path {}", w2, "/node1");
@@ -354,25 +358,25 @@ public class RemoveWatchesTest extends ClientBase {
         MyWatcher w3 = new MyWatcher("/node1", 2);
 
         try {
-            removeWatches(zk2, "/node1", w3, WatcherType.Any, false, Code.NOWATCHER);
+            removeWatches(zk2, "/node1", w3, WatcherType.Any, false, Code.NOWATCHER, useAsync);
             fail("Should throw exception as given watcher doesn't exists");
         } catch (KeeperException.NoWatcherException nwe) {
             // expected
         }
         try {
-            removeWatches(zk2, "/node1", w3, WatcherType.Children, false, Code.NOWATCHER);
+            removeWatches(zk2, "/node1", w3, WatcherType.Children, false, Code.NOWATCHER, useAsync);
             fail("Should throw exception as given watcher doesn't exists");
         } catch (KeeperException.NoWatcherException nwe) {
             // expected
         }
         try {
-            removeWatches(zk2, "/node1", w3, WatcherType.Data, false, Code.NOWATCHER);
+            removeWatches(zk2, "/node1", w3, WatcherType.Data, false, Code.NOWATCHER, useAsync);
             fail("Should throw exception as given watcher doesn't exists");
         } catch (KeeperException.NoWatcherException nwe) {
             // expected
         }
         try {
-            removeWatches(zk2, "/nonexists", w3, WatcherType.Data, false, Code.NOWATCHER);
+            removeWatches(zk2, "/nonexists", w3, WatcherType.Data, false, Code.NOWATCHER, useAsync);
             fail("Should throw exception as given watcher doesn't exists");
         } catch (KeeperException.NoWatcherException nwe) {
             // expected
@@ -383,91 +387,99 @@ public class RemoveWatchesTest extends ClientBase {
      * Test verifies WatcherType.Any - removes only the configured data watcher
      * function
      */
-    @Test(timeout = 90000)
-    public void testRemoveAnyDataWatcher() throws Exception {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testRemoveAnyDataWatcher(boolean useAsync) throws Exception {
         zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         MyWatcher w1 = new MyWatcher("/node1", 1);
         MyWatcher w2 = new MyWatcher("/node1", 2);
         // Add multiple data watches
         LOG.info("Adding data watcher {} on path {}", w1, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+        assertNotNull(zk2.exists("/node1", w1), "Didn't set data watches");
         LOG.info("Adding data watcher {} on path {}", w2, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w2));
+        assertNotNull(zk2.exists("/node1", w2), "Didn't set data watches");
         // Add child watch
         LOG.info("Adding child watcher {} on path {}", w2, "/node1");
         zk2.getChildren("/node1", w2);
-        removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK);
-        assertTrue("Didn't remove data watcher", w1.matches());
-        assertEquals("Didn't find child watcher", 1, zk2.getChildWatches().size());
-        assertEquals("Didn't find data watcher", 1, zk2.getDataWatches().size());
-        removeWatches(zk2, "/node1", w2, WatcherType.Any, false, Code.OK);
-        assertTrue("Didn't remove child watcher", w2.matches());
+        removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK, useAsync);
+        assertTrue(w1.matches(), "Didn't remove data watcher");
+        assertEquals(1, zk2.getChildWatches().size(), "Didn't find child watcher");
+        assertEquals(1, zk2.getDataWatches().size(), "Didn't find data watcher");
+        removeWatches(zk2, "/node1", w2, WatcherType.Any, false, Code.OK, useAsync);
+        assertTrue(w2.matches(), "Didn't remove child watcher");
     }
 
     /**
      * Test verifies WatcherType.Any - removes only the configured child watcher
      * function
      */
-    @Test(timeout = 90000)
-    public void testRemoveAnyChildWatcher() throws Exception {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testRemoveAnyChildWatcher(boolean useAsync) throws Exception {
         zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         MyWatcher w1 = new MyWatcher("/node1", 2);
         MyWatcher w2 = new MyWatcher("/node1", 1);
         LOG.info("Adding data watcher {} on path {}", w1, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+        assertNotNull(zk2.exists("/node1", w1), "Didn't set data watches");
         // Add multiple child watches
         LOG.info("Adding child watcher {} on path {}", w1, "/node1");
         zk2.getChildren("/node1", w2);
         LOG.info("Adding child watcher {} on path {}", w2, "/node1");
         zk2.getChildren("/node1", w1);
-        removeWatches(zk2, "/node1", w2, WatcherType.Any, false, Code.OK);
-        assertTrue("Didn't remove child watcher", w2.matches());
-        assertEquals("Didn't find child watcher", 1, zk2.getChildWatches().size());
-        assertEquals("Didn't find data watcher", 1, zk2.getDataWatches().size());
-        removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK);
-        assertTrue("Didn't remove watchers", w1.matches());
+        removeWatches(zk2, "/node1", w2, WatcherType.Any, false, Code.OK, useAsync);
+        assertTrue(w2.matches(), "Didn't remove child watcher");
+        assertEquals(1, zk2.getChildWatches().size(), "Didn't find child watcher");
+        assertEquals(1, zk2.getDataWatches().size(), "Didn't find data watcher");
+        removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK, useAsync);
+        assertTrue(w1.matches(), "Didn't remove watchers");
     }
 
     /**
      * Test verifies when there is no server connection. Remove watches when
      * local=true, otw should retain it
      */
-    @Test(timeout = 90000)
-    public void testRemoveWatcherWhenNoConnection() throws Exception {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testRemoveWatcherWhenNoConnection(boolean useAsync) throws Exception {
         zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         MyWatcher w1 = new MyWatcher("/node1", 2);
         MyWatcher w2 = new MyWatcher("/node1", 1);
         LOG.info("Adding data watcher {} on path {}", w1, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+        assertNotNull(zk2.exists("/node1", w1), "Didn't set data watches");
         // Add multiple child watches
         LOG.info("Adding child watcher {} on path {}", w1, "/node1");
         zk2.getChildren("/node1", w1);
         LOG.info("Adding child watcher {} on path {}", w1, "/node1");
         zk2.getChildren("/node1", w2);
         stopServer();
-        removeWatches(zk2, "/node1", w2, WatcherType.Any, true, Code.OK);
-        assertTrue("Didn't remove child watcher", w2.matches());
-        assertFalse("Shouldn't remove data watcher", w1.matches());
+        removeWatches(zk2, "/node1", w2, WatcherType.Any, true, Code.OK, useAsync);
+        assertTrue(w2.matches(), "Didn't remove child watcher");
+        assertFalse(w1.matches(), "Shouldn't remove data watcher");
         try {
-            removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.CONNECTIONLOSS);
+            removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.CONNECTIONLOSS, useAsync);
             fail("Should throw exception as last watch removal requires server connection");
         } catch (KeeperException.ConnectionLossException nwe) {
             // expected
         }
-        assertFalse("Shouldn't remove data watcher", w1.matches());
+        assertFalse(w1.matches(), "Shouldn't remove data watcher");
 
         // when local=true, here if connection not available, simply removes
         // from local session
-        removeWatches(zk2, "/node1", w1, WatcherType.Any, true, Code.OK);
-        assertTrue("Didn't remove data watcher", w1.matches());
+        removeWatches(zk2, "/node1", w1, WatcherType.Any, true, Code.OK, useAsync);
+        assertTrue(w1.matches(), "Didn't remove data watcher");
     }
 
     /**
      * Test verifies many pre-node watchers. Also, verifies internal
      * datastructure 'watchManager.existWatches'
      */
-    @Test(timeout = 90000)
-    public void testManyPreNodeWatchers() throws Exception {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testManyPreNodeWatchers(boolean useAsync) throws Exception {
         int count = 50;
         List<MyWatcher> wList = new ArrayList<MyWatcher>(count);
         MyWatcher w;
@@ -480,21 +492,23 @@ public class RemoveWatchesTest extends ClientBase {
             LOG.info("Adding pre node watcher {} on path {}", w, nodePath);
             zk1.exists(nodePath, w);
         }
-        assertEquals("Failed to add watchers!", count, zk1.getExistWatches().size());
+        assertEquals(count, zk1.getExistWatches().size(), "Failed to add watchers!");
         for (int i = 0; i < count; i++) {
             final MyWatcher watcher = wList.get(i);
-            removeWatches(zk1, path + i, watcher, WatcherType.Data, false, Code.OK);
-            assertTrue("Didn't remove data watcher", watcher.matches());
+            removeWatches(zk1, path + i, watcher, WatcherType.Data, false, Code.OK, useAsync);
+            assertTrue(watcher.matches(), "Didn't remove data watcher");
         }
-        assertEquals("Didn't remove watch references!", 0, zk1.getExistWatches().size());
+        assertEquals(0, zk1.getExistWatches().size(), "Didn't remove watch references!");
     }
 
     /**
      * Test verifies many child watchers. Also, verifies internal datastructure
      * 'watchManager.childWatches'
      */
-    @Test(timeout = 90000)
-    public void testManyChildWatchers() throws Exception {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testManyChildWatchers(boolean useAsync) throws Exception {
         int count = 50;
         List<MyWatcher> wList = new ArrayList<MyWatcher>(count);
         MyWatcher w;
@@ -514,21 +528,23 @@ public class RemoveWatchesTest extends ClientBase {
             zk1.getChildren(nodePath, w);
             nodePath += "/";
         }
-        assertEquals("Failed to add watchers!", count, zk1.getChildWatches().size());
+        assertEquals(count, zk1.getChildWatches().size(), "Failed to add watchers!");
         for (int i = 0; i < count; i++) {
             final MyWatcher watcher = wList.get(i);
-            removeWatches(zk1, path + i, watcher, WatcherType.Children, false, Code.OK);
-            assertTrue("Didn't remove child watcher", watcher.matches());
+            removeWatches(zk1, path + i, watcher, WatcherType.Children, false, Code.OK, useAsync);
+            assertTrue(watcher.matches(), "Didn't remove child watcher");
         }
-        assertEquals("Didn't remove watch references!", 0, zk1.getChildWatches().size());
+        assertEquals(0, zk1.getChildWatches().size(), "Didn't remove watch references!");
     }
 
     /**
      * Test verifies many data watchers. Also, verifies internal datastructure
      * 'watchManager.dataWatches'
      */
-    @Test(timeout = 90000)
-    public void testManyDataWatchers() throws Exception {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testManyDataWatchers(boolean useAsync) throws Exception {
         int count = 50;
         List<MyWatcher> wList = new ArrayList<MyWatcher>(count);
         MyWatcher w;
@@ -544,21 +560,23 @@ public class RemoveWatchesTest extends ClientBase {
             zk1.getData(nodePath, w, null);
             nodePath += "/";
         }
-        assertEquals("Failed to add watchers!", count, zk1.getDataWatches().size());
+        assertEquals(count, zk1.getDataWatches().size(), "Failed to add watchers!");
         for (int i = 0; i < count; i++) {
             final MyWatcher watcher = wList.get(i);
-            removeWatches(zk1, path + i, watcher, WatcherType.Data, false, Code.OK);
-            assertTrue("Didn't remove data watcher", watcher.matches());
+            removeWatches(zk1, path + i, watcher, WatcherType.Data, false, Code.OK, useAsync);
+            assertTrue(watcher.matches(), "Didn't remove data watcher");
         }
-        assertEquals("Didn't remove watch references!", 0, zk1.getDataWatches().size());
+        assertEquals(0, zk1.getDataWatches().size(), "Didn't remove watch references!");
     }
 
     /**
      * Test verifies removal of many watchers locally when no connection and
      * WatcherType#Any. Also, verifies internal watchManager datastructures
      */
-    @Test(timeout = 90000)
-    public void testManyWatchersWhenNoConnection() throws Exception {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testManyWatchersWhenNoConnection(boolean useAsync) throws Exception {
         int count = 3;
         List<MyWatcher> wList = new ArrayList<MyWatcher>(count);
         MyWatcher w;
@@ -578,7 +596,7 @@ public class RemoveWatchesTest extends ClientBase {
             zk1.getChildren(nodePath, w);
             nodePath += "/";
         }
-        assertEquals("Failed to add watchers!", count, zk1.getChildWatches().size());
+        assertEquals(count, zk1.getChildWatches().size(), "Failed to add watchers!");
 
         // Data watcher
         for (int i = 0; i < count; i++) {
@@ -588,22 +606,24 @@ public class RemoveWatchesTest extends ClientBase {
             zk1.getData(nodePath, w, null);
             nodePath += "/";
         }
-        assertEquals("Failed to add watchers!", count, zk1.getDataWatches().size());
+        assertEquals(count, zk1.getDataWatches().size(), "Failed to add watchers!");
         stopServer();
         for (int i = 0; i < count; i++) {
             final MyWatcher watcher = wList.get(i);
-            removeWatches(zk1, path + i, watcher, WatcherType.Any, true, Code.OK);
-            assertTrue("Didn't remove watcher", watcher.matches());
+            removeWatches(zk1, path + i, watcher, WatcherType.Any, true, Code.OK, useAsync);
+            assertTrue(watcher.matches(), "Didn't remove watcher");
         }
-        assertEquals("Didn't remove watch references!", 0, zk1.getChildWatches().size());
-        assertEquals("Didn't remove watch references!", 0, zk1.getDataWatches().size());
+        assertEquals(0, zk1.getChildWatches().size(), "Didn't remove watch references!");
+        assertEquals(0, zk1.getDataWatches().size(), "Didn't remove watch references!");
     }
 
     /**
      * Test verifies removing watcher having namespace
      */
-    @Test(timeout = 90000)
-    public void testChRootRemoveWatcher() throws Exception {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testChRootRemoveWatcher(boolean useAsync) throws Exception {
         // creating the subtree for chRoot clients.
         String chRoot = "/appsX";
         zk1.create("/appsX", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
@@ -622,17 +642,17 @@ public class RemoveWatchesTest extends ClientBase {
         MyWatcher w1 = new MyWatcher("/node1", 2);
         MyWatcher w2 = new MyWatcher("/node1", 1);
         LOG.info("Adding data watcher {} on path {}", w1, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+        assertNotNull(zk2.exists("/node1", w1), "Didn't set data watches");
         // Add multiple child watches
         LOG.info("Adding child watcher {} on path {}", w1, "/node1");
         zk2.getChildren("/node1", w2);
         LOG.info("Adding child watcher {} on path {}", w2, "/node1");
         zk2.getChildren("/node1", w1);
-        removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK);
-        assertTrue("Didn't remove child watcher", w1.matches());
-        assertEquals("Didn't find child watcher", 1, zk2.getChildWatches().size());
-        removeWatches(zk2, "/node1", w2, WatcherType.Any, false, Code.OK);
-        assertTrue("Didn't remove child watcher", w2.matches());
+        removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK, useAsync);
+        assertTrue(w1.matches(), "Didn't remove child watcher");
+        assertEquals(1, zk2.getChildWatches().size(), "Didn't find child watcher");
+        removeWatches(zk2, "/node1", w2, WatcherType.Any, false, Code.OK, useAsync);
+        assertTrue(w2.matches(), "Didn't remove child watcher");
     }
 
     /**
@@ -656,8 +676,10 @@ public class RemoveWatchesTest extends ClientBase {
      * we would just return ZOK even if no watch was removed.
      *
      */
-    @Test(timeout = 90000)
-    public void testNoWatcherServerException() throws InterruptedException, IOException, TimeoutException {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testNoWatcherServerException(boolean useAsync) throws InterruptedException, IOException, TimeoutException {
         CountdownWatcher watcher = new CountdownWatcher();
         ZooKeeper zk = spy(new ZooKeeper(hostPort, CONNECTION_TIMEOUT, watcher));
         MyWatchManager watchManager = new MyWatchManager(false, watcher);
@@ -681,11 +703,13 @@ public class RemoveWatchesTest extends ClientBase {
     /**
      * Test verifies given watcher doesn't exists!
      */
-    @Test(timeout = 90000)
-    public void testRemoveAllNoWatcherException() throws IOException, InterruptedException, KeeperException {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testRemoveAllNoWatcherException(boolean useAsync) throws IOException, InterruptedException, KeeperException {
         zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         try {
-            removeAllWatches(zk2, "/node1", WatcherType.Any, false, Code.NOWATCHER);
+            removeAllWatches(zk2, "/node1", WatcherType.Any, false, Code.NOWATCHER, useAsync);
             fail("Should throw exception as given watcher doesn't exists");
         } catch (KeeperException.NoWatcherException nwe) {
             // expected
@@ -695,8 +719,10 @@ public class RemoveWatchesTest extends ClientBase {
     /**
      * Test verifies null watcher
      */
-    @Test(timeout = 30000)
-    public void testNullWatcherReference() throws Exception {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 30)
+    public void testNullWatcherReference(boolean useAsync) throws Exception {
         zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         try {
             if (useAsync) {
@@ -714,8 +740,10 @@ public class RemoveWatchesTest extends ClientBase {
      * Test verifies WatcherType.Data - removes only the configured data watcher
      * function
      */
-    @Test(timeout = 90000)
-    public void testRemoveWhenMultipleDataWatchesOnAPath() throws Exception {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testRemoveWhenMultipleDataWatchesOnAPath(boolean useAsync) throws Exception {
         zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         final CountDownLatch dataWatchCount = new CountDownLatch(1);
         final CountDownLatch rmWatchCount = new CountDownLatch(1);
@@ -731,24 +759,26 @@ public class RemoveWatchesTest extends ClientBase {
         };
         // Add multiple data watches
         LOG.info("Adding data watcher {} on path {}", w1, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+        assertNotNull(zk2.exists("/node1", w1), "Didn't set data watches");
         LOG.info("Adding data watcher {} on path {}", w2, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w2));
+        assertNotNull(zk2.exists("/node1", w2), "Didn't set data watches");
 
-        removeWatches(zk2, "/node1", w1, WatcherType.Data, false, Code.OK);
-        assertTrue("Didn't remove data watcher", rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+        removeWatches(zk2, "/node1", w1, WatcherType.Data, false, Code.OK, useAsync);
+        assertTrue(rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS), "Didn't remove data watcher");
 
         zk1.setData("/node1", "test".getBytes(), -1);
         LOG.info("Waiting for data watchers to be notified");
-        assertTrue("Didn't get data watch notification!", dataWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+        assertTrue(dataWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS), "Didn't get data watch notification!");
     }
 
     /**
      * Test verifies WatcherType.Children - removes only the configured child
      * watcher function
      */
-    @Test(timeout = 90000)
-    public void testRemoveWhenMultipleChildWatchesOnAPath() throws Exception {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testRemoveWhenMultipleChildWatchesOnAPath(boolean useAsync) throws Exception {
         zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         final CountDownLatch childWatchCount = new CountDownLatch(1);
         final CountDownLatch rmWatchCount = new CountDownLatch(1);
@@ -764,24 +794,26 @@ public class RemoveWatchesTest extends ClientBase {
         };
         // Add multiple child watches
         LOG.info("Adding child watcher {} on path {}", w1, "/node1");
-        assertEquals("Didn't set child watches", 0, zk2.getChildren("/node1", w1).size());
+        assertEquals(0, zk2.getChildren("/node1", w1).size(), "Didn't set child watches");
         LOG.info("Adding child watcher {} on path {}", w2, "/node1");
-        assertEquals("Didn't set child watches", 0, zk2.getChildren("/node1", w2).size());
+        assertEquals(0, zk2.getChildren("/node1", w2).size(), "Didn't set child watches");
 
-        removeWatches(zk2, "/node1", w1, WatcherType.Children, false, Code.OK);
-        assertTrue("Didn't remove child watcher", rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+        removeWatches(zk2, "/node1", w1, WatcherType.Children, false, Code.OK, useAsync);
+        assertTrue(rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS), "Didn't remove child watcher");
 
         zk1.create("/node1/node2", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         LOG.info("Waiting for child watchers to be notified");
-        assertTrue("Didn't get child watch notification!", childWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+        assertTrue(childWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS), "Didn't get child watch notification!");
     }
 
     /**
      * Test verifies WatcherType.Data - removes only the configured data watcher
      * function
      */
-    @Test(timeout = 90000)
-    public void testRemoveAllDataWatchesOnAPath() throws Exception {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testRemoveAllDataWatchesOnAPath(boolean useAsync) throws Exception {
         zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         final CountDownLatch dWatchCount = new CountDownLatch(2);
         final CountDownLatch rmWatchCount = new CountDownLatch(2);
@@ -811,23 +843,25 @@ public class RemoveWatchesTest extends ClientBase {
         };
         // Add multiple data watches
         LOG.info("Adding data watcher {} on path {}", w1, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+        assertNotNull(zk2.exists("/node1", w1), "Didn't set data watches");
         LOG.info("Adding data watcher {} on path {}", w2, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w2));
+        assertNotNull(zk2.exists("/node1", w2), "Didn't set data watches");
 
-        assertTrue("Server session is not a watcher", isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Data));
-        removeAllWatches(zk2, "/node1", WatcherType.Data, false, Code.OK);
-        assertTrue("Didn't remove data watcher", rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+        assertTrue(isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Data), "Server session is not a watcher");
+        removeAllWatches(zk2, "/node1", WatcherType.Data, false, Code.OK, useAsync);
+        assertTrue(rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS), "Didn't remove data watcher");
 
-        assertFalse("Server session is still a watcher after removal", isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Data));
+        assertFalse(isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Data), "Server session is still a watcher after removal");
     }
 
     /**
      * Test verifies WatcherType.Children - removes only the configured child
      * watcher function
      */
-    @Test(timeout = 90000)
-    public void testRemoveAllChildWatchesOnAPath() throws Exception {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testRemoveAllChildWatchesOnAPath(boolean useAsync) throws Exception {
         zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         final CountDownLatch cWatchCount = new CountDownLatch(2);
         final CountDownLatch rmWatchCount = new CountDownLatch(2);
@@ -857,23 +891,25 @@ public class RemoveWatchesTest extends ClientBase {
         };
         // Add multiple child watches
         LOG.info("Adding child watcher {} on path {}", w1, "/node1");
-        assertEquals("Didn't set child watches", 0, zk2.getChildren("/node1", w1).size());
+        assertEquals(0, zk2.getChildren("/node1", w1).size(), "Didn't set child watches");
         LOG.info("Adding child watcher {} on path {}", w2, "/node1");
-        assertEquals("Didn't set child watches", 0, zk2.getChildren("/node1", w2).size());
+        assertEquals(0, zk2.getChildren("/node1", w2).size(), "Didn't set child watches");
 
-        assertTrue("Server session is not a watcher", isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Children));
-        removeAllWatches(zk2, "/node1", WatcherType.Children, false, Code.OK);
-        assertTrue("Didn't remove child watcher", rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+        assertTrue(isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Children), "Server session is not a watcher");
+        removeAllWatches(zk2, "/node1", WatcherType.Children, false, Code.OK, useAsync);
+        assertTrue(rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS), "Didn't remove child watcher");
 
-        assertFalse("Server session is still a watcher after removal", isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Children));
+        assertFalse(isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Children), "Server session is still a watcher after removal");
     }
 
     /**
      * Test verifies WatcherType.Any - removes all the configured child,data
      * watcher functions
      */
-    @Test(timeout = 90000)
-    public void testRemoveAllWatchesOnAPath() throws Exception {
+    @ParameterizedTest
+    @ValueSource(booleans = {true, false})
+    @Timeout(value = 90)
+    public void testRemoveAllWatchesOnAPath(boolean useAsync) throws Exception {
         zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         final CountDownLatch watchCount = new CountDownLatch(2);
         final CountDownLatch rmWatchCount = new CountDownLatch(4);
@@ -907,21 +943,21 @@ public class RemoveWatchesTest extends ClientBase {
         };
         // Add multiple child watches
         LOG.info("Adding child watcher {} on path {}", w1, "/node1");
-        assertEquals("Didn't set child watches", 0, zk2.getChildren("/node1", w1).size());
+        assertEquals(0, zk2.getChildren("/node1", w1).size(), "Didn't set child watches");
         LOG.info("Adding child watcher {} on path {}", w2, "/node1");
-        assertEquals("Didn't set child watches", 0, zk2.getChildren("/node1", w2).size());
+        assertEquals(0, zk2.getChildren("/node1", w2).size(), "Didn't set child watches");
 
         // Add multiple data watches
         LOG.info("Adding data watcher {} on path {}", w1, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+        assertNotNull(zk2.exists("/node1", w1), "Didn't set data watches");
         LOG.info("Adding data watcher {} on path {}", w2, "/node1");
-        assertNotNull("Didn't set data watches", zk2.exists("/node1", w2));
+        assertNotNull(zk2.exists("/node1", w2), "Didn't set data watches");
 
-        assertTrue("Server session is not a watcher", isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Data));
-        removeAllWatches(zk2, "/node1", WatcherType.Any, false, Code.OK);
-        assertTrue("Didn't remove data watcher", rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
-        assertFalse("Server session is still a watcher after removal", isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Data));
-        assertEquals("Received watch notification after removal!", 2, watchCount.getCount());
+        assertTrue(isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Data), "Server session is not a watcher");
+        removeAllWatches(zk2, "/node1", WatcherType.Any, false, Code.OK, useAsync);
+        assertTrue(rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS), "Didn't remove data watcher");
+        assertFalse(isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Data), "Server session is still a watcher after removal");
+        assertEquals(2, watchCount.getCount(), "Received watch notification after removal!");
     }
 
     private static class MyWatchManager extends ZKWatchManager {

+ 11 - 11
zookeeper-server/src/test/java/org/apache/zookeeper/SaslAuthTest.java

@@ -18,9 +18,9 @@
 
 package org.apache.zookeeper;
 
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.File;
 import java.io.FileWriter;
 import java.io.IOException;
@@ -36,13 +36,13 @@ import org.apache.zookeeper.ZooDefs.Ids;
 import org.apache.zookeeper.data.ACL;
 import org.apache.zookeeper.data.Id;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
 
 public class SaslAuthTest extends ClientBase {
 
-    @BeforeClass
+    @BeforeAll
     public static void init() {
         System.setProperty("zookeeper.authProvider.1", "org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
         try {
@@ -83,7 +83,7 @@ public class SaslAuthTest extends ClientBase {
         return jaasContent.toString();
     }
 
-    @AfterClass
+    @AfterAll
     public static void clean() {
         System.clearProperty("zookeeper.authProvider.1");
         System.clearProperty("java.security.auth.login.config");
@@ -187,7 +187,7 @@ public class SaslAuthTest extends ClientBase {
                     // do nothing
                 }
             }
-            assertTrue("ZNode creation is failing continuously after Sasl auth failure.", success);
+            assertTrue(success, "ZNode creation is failing continuously after Sasl auth failure.");
 
         } finally {
             zk.close();
@@ -234,8 +234,8 @@ public class SaslAuthTest extends ClientBase {
             EventThread eventThread = (EventThread) eventThreadField.get(clientCnxn);
             sendThread.join(CONNECTION_TIMEOUT);
             eventThread.join(CONNECTION_TIMEOUT);
-            assertFalse("SendThread did not shutdown after authFail", sendThread.isAlive());
-            assertFalse("EventThread did not shutdown after authFail", eventThread.isAlive());
+            assertFalse(sendThread.isAlive(), "SendThread did not shutdown after authFail");
+            assertFalse(eventThread.isAlive(), "EventThread did not shutdown after authFail");
         } finally {
             if (zk != null) {
                 zk.close();

+ 17 - 12
zookeeper-server/src/test/java/org/apache/zookeeper/ServerConfigTest.java

@@ -18,30 +18,33 @@
 
 package org.apache.zookeeper;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 import java.io.File;
 import org.apache.zookeeper.server.ServerConfig;
 import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class ServerConfigTest {
 
     private ServerConfig serverConfig;
 
-    @Before
+    @BeforeEach
     public void setUp() {
         serverConfig = new ServerConfig();
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testFewArguments() {
-        String[] args = {"2181"};
-        serverConfig.parse(args);
+        assertThrows(IllegalArgumentException.class, () -> {
+            String[] args = {"2181"};
+            serverConfig.parse(args);
+        });
     }
 
     @Test
@@ -55,10 +58,12 @@ public class ServerConfigTest {
         assertEquals(10000, serverConfig.getMaxClientCnxns());
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testTooManyArguments() {
-        String[] args = {"2181", "/data/dir", "60000", "10000", "9999"};
-        serverConfig.parse(args);
+        assertThrows(IllegalArgumentException.class, () -> {
+            String[] args = {"2181", "/data/dir", "60000", "10000", "9999"};
+            serverConfig.parse(args);
+        });
     }
 
     @Test

+ 0 - 62
zookeeper-server/src/test/java/org/apache/zookeeper/ZKParameterized.java

@@ -1,62 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper;
-
-import java.util.List;
-import org.junit.runners.model.FrameworkMethod;
-import org.junit.runners.model.InitializationError;
-import org.junit.runners.model.Statement;
-import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters;
-import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParametersFactory;
-import org.junit.runners.parameterized.TestWithParameters;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ZKParameterized {
-
-    private static final Logger LOG = LoggerFactory.getLogger(ZKParameterized.class);
-
-    public static class RunnerFactory extends BlockJUnit4ClassRunnerWithParametersFactory {
-
-        @Override
-        public org.junit.runner.Runner createRunnerForTestWithParameters(TestWithParameters test) throws InitializationError {
-            return new ZKParameterized.Runner(test);
-        }
-
-    }
-
-    public static class Runner extends BlockJUnit4ClassRunnerWithParameters {
-
-        public Runner(TestWithParameters test) throws InitializationError {
-            super(test);
-        }
-
-        @Override
-        protected List<FrameworkMethod> computeTestMethods() {
-            return JUnit4ZKTestRunner.computeTestMethodsForClass(getTestClass().getJavaClass(), super.computeTestMethods());
-        }
-
-        @Override
-        protected Statement methodInvoker(FrameworkMethod method, Object test) {
-            return new JUnit4ZKTestRunner.LoggedInvokeMethod(method, test);
-        }
-
-    }
-
-}

+ 28 - 49
zookeeper-server/src/test/java/org/apache/zookeeper/ZKTestCase.java

@@ -18,16 +18,15 @@
 
 package org.apache.zookeeper;
 
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.File;
 import java.time.LocalDateTime;
 import org.apache.zookeeper.util.ServiceUtils;
-import org.junit.BeforeClass;
-import org.junit.Rule;
-import org.junit.rules.TestWatcher;
-import org.junit.runner.Description;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.TestInfo;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -37,7 +36,6 @@ import org.slf4j.LoggerFactory;
  * Basic utilities shared by all tests. Also logging of various events during
  * the test execution (start/stop/success/failure/etc...)
  */
-@RunWith(JUnit4ZKTestRunner.class)
 public class ZKTestCase {
 
     protected static final File testBaseDir = new File(System.getProperty("build.test.dir", "build"));
@@ -54,54 +52,35 @@ public class ZKTestCase {
         return testName;
     }
 
-    @BeforeClass
+    @BeforeAll
     public static void before() {
         if (!testBaseDir.exists()) {
-            assertTrue(
-                "Cannot properly create test base directory " + testBaseDir.getAbsolutePath(),
-                testBaseDir.mkdirs());
+            assertTrue(testBaseDir.mkdirs(),
+                "Cannot properly create test base directory " + testBaseDir.getAbsolutePath());
         } else if (!testBaseDir.isDirectory()) {
-            assertTrue(
-                "Cannot properly delete file with duplicate name of test base directory " + testBaseDir.getAbsolutePath(),
-                testBaseDir.delete());
-            assertTrue(
-                "Cannot properly create test base directory " + testBaseDir.getAbsolutePath(),
-                testBaseDir.mkdirs());
+            assertTrue(testBaseDir.delete(),
+                "Cannot properly delete file with duplicate name of test base directory " + testBaseDir.getAbsolutePath());
+            assertTrue(testBaseDir.mkdirs(),
+                "Cannot properly create test base directory " + testBaseDir.getAbsolutePath());
         }
     }
 
-    @Rule
-    public TestWatcher watchman = new TestWatcher() {
-
-        @Override
-        public void starting(Description method) {
-            // By default, disable starting a JettyAdminServer in tests to avoid
-            // accidentally attempting to start multiple admin servers on the
-            // same port.
-            System.setProperty("zookeeper.admin.enableServer", "false");
-            // ZOOKEEPER-2693 disables all 4lw by default.
-            // Here we enable the 4lw which ZooKeeper tests depends.
-            System.setProperty("zookeeper.4lw.commands.whitelist", "*");
-            testName = method.getMethodName();
-            LOG.info("STARTING {}", testName);
-        }
-
-        @Override
-        public void finished(Description method) {
-            LOG.info("FINISHED {}", testName);
-        }
-
-        @Override
-        public void succeeded(Description method) {
-            LOG.info("SUCCEEDED {}", testName);
-        }
-
-        @Override
-        public void failed(Throwable e, Description method) {
-            LOG.error("FAILED {}", testName, e);
-        }
+    @BeforeEach
+    public void starting(TestInfo testInfo) {
+        // By default, disable starting a JettyAdminServer in tests to avoid
+        // accidentally attempting to start multiple admin servers on the
+        // same port.
+        System.setProperty("zookeeper.admin.enableServer", "false");
+        // ZOOKEEPER-2693 disables all 4lw by default.
+        // Here we enable the 4lw which ZooKeeper tests depends.
+        System.setProperty("zookeeper.4lw.commands.whitelist", "*");
+        LOG.info("STARTING {}", testInfo.getTestMethod());
+    }
 
-    };
+    @AfterEach
+    public void finished(TestInfo testInfo) {
+        LOG.info("FINISHED {}", testInfo.getTestMethod());
+    }
 
     public interface WaitForCondition {
 

+ 6 - 6
zookeeper-server/src/test/java/org/apache/zookeeper/ZKUtilTest.java

@@ -18,21 +18,21 @@
 
 package org.apache.zookeeper;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
 import static org.junit.Assume.assumeTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
 import java.io.File;
 import java.io.IOException;
 import java.util.UUID;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
 
 public class ZKUtilTest {
 
     private static final File testData = new File(System.getProperty("test.data.dir", "build/test/data"));
 
-    @BeforeClass
+    @BeforeAll
     public static void init() {
         testData.mkdirs();
     }

+ 42 - 44
zookeeper-server/src/test/java/org/apache/zookeeper/ZooKeeperTest.java

@@ -18,11 +18,11 @@
 
 package org.apache.zookeeper;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.PrintStream;
@@ -48,7 +48,7 @@ import org.apache.zookeeper.data.ACL;
 import org.apache.zookeeper.data.Id;
 import org.apache.zookeeper.data.Stat;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 /**
  *
@@ -66,7 +66,7 @@ public class ZooKeeperTest extends ClientBase {
 
         assertTrue(ZKUtil.deleteRecursive(zk, "/a/c", 1000));
         List<String> children = zk.getChildren("/a", false);
-        assertEquals("1 children - c should be deleted ", 1, children.size());
+        assertEquals(1, children.size(), "1 children - c should be deleted ");
         assertTrue(children.contains("b"));
 
         assertTrue(ZKUtil.deleteRecursive(zk, "/a", 1000));
@@ -89,12 +89,12 @@ public class ZooKeeperTest extends ClientBase {
 
         assertFalse(ZKUtil.deleteRecursive(zk, "/a/c", 1000));
         List<String> children = zk.getChildren("/a", false);
-        assertEquals("2 children - c should fail to be deleted ", 2, children.size());
+        assertEquals(2, children.size(), "2 children - c should fail to be deleted ");
         assertTrue(children.contains("b"));
 
         assertTrue(ZKUtil.deleteRecursive(zk, "/a/b", 1000));
         children = zk.getChildren("/a", false);
-        assertEquals("1 children - b should be deleted ", 1, children.size());
+        assertEquals(1, children.size(), "1 children - b should be deleted ");
 
         // acquire immunity to poison
         zk.addAuthInfo(deleteProtection.getId().getScheme(), "user:test".getBytes());
@@ -125,7 +125,7 @@ public class ZooKeeperTest extends ClientBase {
         }
         List<String> children = zk.getChildren("/a", false);
 
-        assertEquals("2 children - b & c should be present ", 2, children.size());
+        assertEquals(2, children.size(), "2 children - b & c should be present ");
         assertTrue(children.contains("b"));
         assertTrue(children.contains("c"));
     }
@@ -149,7 +149,7 @@ public class ZooKeeperTest extends ClientBase {
 
         List<String> children = zk.getChildren("/a", false);
 
-        assertEquals("2 children - b & c should be present ", children.size(), 2);
+        assertEquals(children.size(), 2, "2 children - b & c should be present ");
         assertTrue(children.contains("b"));
         assertTrue(children.contains("c"));
 
@@ -182,7 +182,7 @@ public class ZooKeeperTest extends ClientBase {
         }
         List<String> children = zk.getChildren("/a", false);
 
-        assertEquals("2 children - b & c should be present ", children.size(), 2);
+        assertEquals(children.size(), 2, "2 children - b & c should be present ");
         assertTrue(children.contains("b"));
         assertTrue(children.contains("c"));
 
@@ -225,9 +225,9 @@ public class ZooKeeperTest extends ClientBase {
         ZooKeeperMain zkMain = new ZooKeeperMain(zk);
         String cmdstring = "      ls       /  ";
         zkMain.cl.parseCommand(cmdstring);
-        assertEquals("Spaces also considered as characters", zkMain.cl.getNumArguments(), 2);
-        assertEquals("ls is not taken as first argument", zkMain.cl.getCmdArgument(0), "ls");
-        assertEquals("/ is not taken as second argument", zkMain.cl.getCmdArgument(1), "/");
+        assertEquals(zkMain.cl.getNumArguments(), 2, "Spaces also considered as characters");
+        assertEquals(zkMain.cl.getCmdArgument(0), "ls", "ls is not taken as first argument");
+        assertEquals(zkMain.cl.getCmdArgument(1), "/", "/ is not taken as second argument");
     }
 
     @Test
@@ -237,10 +237,10 @@ public class ZooKeeperTest extends ClientBase {
         for (String quoteChar : new String[]{"'", "\""}) {
             String cmdstring = String.format("create /node %1$squoted data%1$s", quoteChar);
             zkMain.cl.parseCommand(cmdstring);
-            assertEquals("quotes combine arguments", zkMain.cl.getNumArguments(), 3);
-            assertEquals("create is not taken as first argument", zkMain.cl.getCmdArgument(0), "create");
-            assertEquals("/node is not taken as second argument", zkMain.cl.getCmdArgument(1), "/node");
-            assertEquals("quoted data is not taken as third argument", zkMain.cl.getCmdArgument(2), "quoted data");
+            assertEquals(zkMain.cl.getNumArguments(), 3, "quotes combine arguments");
+            assertEquals(zkMain.cl.getCmdArgument(0), "create", "create is not taken as first argument");
+            assertEquals(zkMain.cl.getCmdArgument(1), "/node", "/node is not taken as second argument");
+            assertEquals(zkMain.cl.getCmdArgument(2), "quoted data", "quoted data is not taken as third argument");
         }
     }
 
@@ -253,13 +253,11 @@ public class ZooKeeperTest extends ClientBase {
             String innerQuotes = quoteChars[1];
             String cmdstring = String.format("create /node %1$s%2$squoted data%2$s%1$s", outerQuotes, innerQuotes);
             zkMain.cl.parseCommand(cmdstring);
-            assertEquals("quotes combine arguments", zkMain.cl.getNumArguments(), 3);
-            assertEquals("create is not taken as first argument", zkMain.cl.getCmdArgument(0), "create");
-            assertEquals("/node is not taken as second argument", zkMain.cl.getCmdArgument(1), "/node");
-            assertEquals(
-                "quoted data is not taken as third argument",
-                zkMain.cl.getCmdArgument(2),
-                innerQuotes + "quoted data" + innerQuotes);
+            assertEquals(zkMain.cl.getNumArguments(), 3, "quotes combine arguments");
+            assertEquals(zkMain.cl.getCmdArgument(0), "create", "create is not taken as first argument");
+            assertEquals(zkMain.cl.getCmdArgument(1), "/node", "/node is not taken as second argument");
+            assertEquals(zkMain.cl.getCmdArgument(2), innerQuotes + "quoted data" + innerQuotes,
+                    "quoted data is not taken as third argument");
         }
     }
 
@@ -269,10 +267,10 @@ public class ZooKeeperTest extends ClientBase {
         ZooKeeperMain zkMain = new ZooKeeperMain(zk);
         String cmdstring = "create /node ''";
         zkMain.cl.parseCommand(cmdstring);
-        assertEquals("empty quotes should produce arguments", zkMain.cl.getNumArguments(), 3);
-        assertEquals("create is not taken as first argument", zkMain.cl.getCmdArgument(0), "create");
-        assertEquals("/node is not taken as second argument", zkMain.cl.getCmdArgument(1), "/node");
-        assertEquals("empty string is not taken as third argument", zkMain.cl.getCmdArgument(2), "");
+        assertEquals(zkMain.cl.getNumArguments(), 3, "empty quotes should produce arguments");
+        assertEquals(zkMain.cl.getCmdArgument(0), "create", "create is not taken as first argument");
+        assertEquals(zkMain.cl.getCmdArgument(1), "/node", "/node is not taken as second argument");
+        assertEquals(zkMain.cl.getCmdArgument(2), "", "empty string is not taken as third argument");
     }
 
     @Test
@@ -281,11 +279,11 @@ public class ZooKeeperTest extends ClientBase {
         ZooKeeperMain zkMain = new ZooKeeperMain(zk);
         String cmdstring = "create /node '' ''";
         zkMain.cl.parseCommand(cmdstring);
-        assertEquals("expected 5 arguments", zkMain.cl.getNumArguments(), 4);
-        assertEquals("create is not taken as first argument", zkMain.cl.getCmdArgument(0), "create");
-        assertEquals("/node is not taken as second argument", zkMain.cl.getCmdArgument(1), "/node");
-        assertEquals("empty string is not taken as third argument", zkMain.cl.getCmdArgument(2), "");
-        assertEquals("empty string is not taken as fourth argument", zkMain.cl.getCmdArgument(3), "");
+        assertEquals(zkMain.cl.getNumArguments(), 4, "expected 5 arguments");
+        assertEquals(zkMain.cl.getCmdArgument(0), "create", "create is not taken as first argument");
+        assertEquals(zkMain.cl.getCmdArgument(1), "/node", "/node is not taken as second argument");
+        assertEquals(zkMain.cl.getCmdArgument(2), "", "empty string is not taken as third argument");
+        assertEquals(zkMain.cl.getCmdArgument(3), "", "empty string is not taken as fourth argument");
     }
 
     @Test
@@ -339,20 +337,20 @@ public class ZooKeeperTest extends ClientBase {
         // create persistent sequential node
         String cmdstring = "create -s /node ";
         zkMain.cl.parseCommand(cmdstring);
-        assertTrue("Doesn't create node without data", zkMain.processZKCmd(zkMain.cl));
+        assertTrue(zkMain.processZKCmd(zkMain.cl), "Doesn't create node without data");
         // create ephemeral node
         cmdstring = "create  -e /node ";
         zkMain.cl.parseCommand(cmdstring);
-        assertTrue("Doesn't create node without data", zkMain.processZKCmd(zkMain.cl));
+        assertTrue(zkMain.processZKCmd(zkMain.cl), "Doesn't create node without data");
         // create ephemeral sequential node
         cmdstring = "create -s -e /node ";
         zkMain.cl.parseCommand(cmdstring);
-        assertTrue("Doesn't create node without data", zkMain.processZKCmd(zkMain.cl));
+        assertTrue(zkMain.processZKCmd(zkMain.cl), "Doesn't create node without data");
         // creating ephemeral with wrong option.
         cmdstring = "create -s y /node";
         zkMain.cl.parseCommand(cmdstring);
         try {
-            assertTrue("Created node with wrong option", zkMain.processZKCmd(zkMain.cl));
+            assertTrue(zkMain.processZKCmd(zkMain.cl), "Created node with wrong option");
             fail("Created the node with wrong option should " + "throw Exception.");
         } catch (MalformedPathException e) {
             assertEquals("Path must start with / character", e.getMessage());
@@ -366,7 +364,7 @@ public class ZooKeeperTest extends ClientBase {
         // create persistent sequential node
         String cmdstring = "create -s /l data ip:10.18.52.144:cdrwa f g h";
         zkMain.cl.parseCommand(cmdstring);
-        assertTrue("Not considering the extra arguments after the acls.", zkMain.processZKCmd(zkMain.cl));
+        assertTrue(zkMain.processZKCmd(zkMain.cl), "Not considering the extra arguments after the acls.");
     }
 
     @Test
@@ -375,7 +373,7 @@ public class ZooKeeperTest extends ClientBase {
         ZooKeeperMain zkMain = new ZooKeeperMain(zk);
         String cmdstring = "create /node2";
         zkMain.cl.parseCommand(cmdstring);
-        assertTrue("Not creating Persistent node.", zkMain.processZKCmd(zkMain.cl));
+        assertTrue(zkMain.processZKCmd(zkMain.cl), "Not creating Persistent node.");
     }
 
     @Test
@@ -390,7 +388,7 @@ public class ZooKeeperTest extends ClientBase {
         zkMain.cl.parseCommand(cmdstring2);
         assertFalse(zkMain.processZKCmd(zkMain.cl));
         zkMain.cl.parseCommand(cmdstring3);
-        assertFalse("", zkMain.processCmd(zkMain.cl));
+        assertFalse(zkMain.processCmd(zkMain.cl), "");
     }
 
     @Test
@@ -526,7 +524,7 @@ public class ZooKeeperTest extends ClientBase {
         command.exec();
 
         String result = byteStream.toString();
-        assertTrue(result, result.contains(StringUtils.joinStrings(expectedResults, LINE_SEPARATOR)));
+        assertTrue(result.contains(StringUtils.joinStrings(expectedResults, LINE_SEPARATOR)), result);
     }
 
     @Test
@@ -671,7 +669,7 @@ public class ZooKeeperTest extends ClientBase {
                 aHostProvider,
                 clientConfig);
             watcher.waitForConnected(CONNECTION_TIMEOUT);
-            assertEquals("Old client session id and new clinet session id must be same", zk.getSessionId(), newZKClient.getSessionId());
+            assertEquals(zk.getSessionId(), newZKClient.getSessionId(), "Old client session id and new clinet session id must be same");
         } finally {
             zk.close();
             newZKClient.close();

+ 2 - 2
zookeeper-server/src/test/java/org/apache/zookeeper/audit/AuditEventTest.java

@@ -17,9 +17,9 @@
  */
 package org.apache.zookeeper.audit;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import org.apache.zookeeper.audit.AuditEvent.Result;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class AuditEventTest {
 

+ 15 - 18
zookeeper-server/src/test/java/org/apache/zookeeper/audit/Log4jAuditLoggerTest.java

@@ -18,7 +18,7 @@
 package org.apache.zookeeper.audit;
 
 import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.LineNumberReader;
@@ -48,11 +48,11 @@ import org.apache.zookeeper.server.ServerCnxn;
 import org.apache.zookeeper.server.quorum.QuorumPeerTestBase;
 import org.apache.zookeeper.test.ClientBase;
 import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 
 public class Log4jAuditLoggerTest extends QuorumPeerTestBase {
@@ -64,7 +64,7 @@ public class Log4jAuditLoggerTest extends QuorumPeerTestBase {
     private static WriterAppender appender;
     private static ByteArrayOutputStream os;
 
-    @BeforeClass
+    @BeforeAll
     public static void setUpBeforeClass() throws Exception {
         System.setProperty(ZKAuditProvider.AUDIT_ENABLE, "true");
         // setup the logger to capture all logs
@@ -83,7 +83,7 @@ public class Log4jAuditLoggerTest extends QuorumPeerTestBase {
         verifyLogs(expectedAuditLog, logs);
     }
 
-    @Before
+    @BeforeEach
     public void setUp() {
         os.reset();
     }
@@ -357,10 +357,9 @@ public class Log4jAuditLoggerTest extends QuorumPeerTestBase {
             logs.add(line);
         }
         os.reset();
-        assertEquals(
+        assertEquals(numberOfLogEntry, logs.size(),
                 "Expected number of log entries are not generated. Logs are "
-                        + logs,
-                numberOfLogEntry, logs.size());
+                        + logs);
         return logs;
 
     }
@@ -393,9 +392,8 @@ public class Log4jAuditLoggerTest extends QuorumPeerTestBase {
 
         // ensure all servers started
         for (int i = 0; i < SERVER_COUNT; i++) {
-            Assert.assertTrue("waiting for server " + i + " being up",
-                    ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
-                            CONNECTION_TIMEOUT));
+            Assertions.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
+                    CONNECTION_TIMEOUT), "waiting for server " + i + " being up");
         }
         return mt;
     }
@@ -410,16 +408,15 @@ public class Log4jAuditLoggerTest extends QuorumPeerTestBase {
             try {
                 Thread.sleep(waitInterval);
             } catch (InterruptedException e) {
-                Assert.fail("CurrentEpoch update failed");
+                Assertions.fail("CurrentEpoch update failed");
             }
             elapsedTime = elapsedTime + waitInterval;
             exists = zooKeeper.exists(path, false);
         }
-        Assert.assertNull("Node " + path + " not deleted in " + timeout + " ms",
-                exists);
+        Assertions.assertNull(exists, "Node " + path + " not deleted in " + timeout + " ms");
     }
 
-    @AfterClass
+    @AfterAll
     public static void tearDownAfterClass() {
         System.clearProperty(ZKAuditProvider.AUDIT_ENABLE);
         for (int i = 0; i < SERVER_COUNT; i++) {

+ 7 - 7
zookeeper-server/src/test/java/org/apache/zookeeper/audit/StandaloneServerAuditTest.java

@@ -19,8 +19,8 @@
 package org.apache.zookeeper.audit;
 
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.LineNumberReader;
@@ -37,16 +37,16 @@ import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.ZooDefs;
 import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
 
 
 
 public class StandaloneServerAuditTest extends ClientBase {
     private static ByteArrayOutputStream os;
 
-    @BeforeClass
+    @BeforeAll
     public static void setup() {
         System.setProperty(ZKAuditProvider.AUDIT_ENABLE, "true");
         // setup the logger to capture all the logs
@@ -59,7 +59,7 @@ public class StandaloneServerAuditTest extends ClientBase {
         zLogger.addAppender(appender);
     }
 
-    @AfterClass
+    @AfterAll
     public static void teardown() {
         System.clearProperty(ZKAuditProvider.AUDIT_ENABLE);
     }

+ 2 - 2
zookeeper-server/src/test/java/org/apache/zookeeper/cli/CommandFactoryTest.java

@@ -18,8 +18,8 @@
 
 package org.apache.zookeeper.cli;
 
-import static org.junit.Assert.assertTrue;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import org.junit.jupiter.api.Test;
 
 /**
  * Unit test for {@link CommandFactory}.

+ 14 - 13
zookeeper-server/src/test/java/org/apache/zookeeper/client/ZKClientConfigTest.java

@@ -25,10 +25,10 @@ import static org.apache.zookeeper.client.ZKClientConfig.SECURE_CLIENT;
 import static org.apache.zookeeper.client.ZKClientConfig.ZK_SASL_CLIENT_USERNAME;
 import static org.apache.zookeeper.client.ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET;
 import static org.apache.zookeeper.client.ZKClientConfig.ZOOKEEPER_SERVER_REALM;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
@@ -36,21 +36,17 @@ import java.io.OutputStream;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Properties;
-import java.util.concurrent.TimeUnit;
 import org.apache.zookeeper.common.ZKConfig;
 import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
-import org.junit.BeforeClass;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.Timeout;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 public class ZKClientConfigTest {
 
     private static final File testData = new File(System.getProperty("test.data.dir", "src/test/resources/data"));
-    @Rule
-    public Timeout timeout = new Timeout(10, TimeUnit.SECONDS);
 
-    @BeforeClass
+    @BeforeAll
     public static void init() {
         if (!testData.exists()) {
             testData.mkdirs();
@@ -58,6 +54,7 @@ public class ZKClientConfigTest {
     }
 
     @Test
+    @Timeout(value = 10)
     public void testDefaultConfiguration() {
         Map<String, String> properties = new HashMap<>();
         properties.put(ZK_SASL_CLIENT_USERNAME, "zookeeper1");
@@ -96,6 +93,7 @@ public class ZKClientConfigTest {
     }
 
     @Test
+    @Timeout(value = 10)
     public void testSystemPropertyValue() {
         String clientName = "zookeeper1";
         System.setProperty(ZK_SASL_CLIENT_USERNAME, clientName);
@@ -110,6 +108,7 @@ public class ZKClientConfigTest {
     }
 
     @Test
+    @Timeout(value = 10)
     public void testReadConfigurationFile() throws IOException, ConfigException {
         File file = File.createTempFile("clientConfig", ".conf", testData);
         file.deleteOnExit();
@@ -137,10 +136,10 @@ public class ZKClientConfigTest {
         // try to delete it now as we have done with the created file, why to
         // wait for deleteOnExit() deletion
         file.delete();
-
     }
 
     @Test
+    @Timeout(value = 10)
     public void testSetConfiguration() {
         ZKClientConfig conf = new ZKClientConfig();
         String defaultValue = conf.getProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY, ZKClientConfig.ENABLE_CLIENT_SASL_DEFAULT);
@@ -153,6 +152,7 @@ public class ZKClientConfigTest {
     }
 
     @Test
+    @Timeout(value = 10)
     public void testIntegerRetrievalFromProperty() {
         ZKClientConfig conf = new ZKClientConfig();
         String prop = "UnSetProperty" + System.currentTimeMillis();
@@ -186,6 +186,7 @@ public class ZKClientConfigTest {
     }
 
     @Test
+    @Timeout(value = 10)
     public void testIntegerRetrievalFromHexadecimalProperty() {
         int hexaValue = 0x3000000;
         String wrongValue = "0xwel";

+ 43 - 43
zookeeper-server/src/test/java/org/apache/zookeeper/common/AtomicFileWritingIdiomTest.java

@@ -18,9 +18,9 @@
 
 package org.apache.zookeeper.common;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
@@ -31,14 +31,14 @@ import java.nio.charset.StandardCharsets;
 import org.apache.zookeeper.ZKTestCase;
 import org.apache.zookeeper.common.AtomicFileWritingIdiom.OutputStreamStatement;
 import org.apache.zookeeper.common.AtomicFileWritingIdiom.WriterStatement;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
 
 public class AtomicFileWritingIdiomTest extends ZKTestCase {
 
     private static File tmpdir;
 
-    @BeforeClass
+    @BeforeAll
     public static void createTmpDir() {
         tmpdir = new File("build/test/tmp");
         tmpdir.mkdirs();
@@ -54,10 +54,10 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
             @Override
             public void write(OutputStream os) throws IOException {
                 os.write("after".getBytes(StandardCharsets.US_ASCII));
-                assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
+                assertTrue(tmp.exists(), "implementation of AtomicFileOutputStream has changed, update the test");
             }
         });
-        assertFalse("tmp file should have been deleted", tmp.exists());
+        assertFalse(tmp.exists(), "tmp file should have been deleted");
         // content changed
         assertEquals("after", getContent(target));
         target.delete();
@@ -73,10 +73,10 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
             @Override
             public void write(Writer os) throws IOException {
                 os.write("after");
-                assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
+                assertTrue(tmp.exists(), "implementation of AtomicFileOutputStream has changed, update the test");
             }
         });
-        assertFalse("tmp file should have been deleted", tmp.exists());
+        assertFalse(tmp.exists(), "tmp file should have been deleted");
         // content changed
         assertEquals("after", getContent(target));
         target.delete();
@@ -95,15 +95,15 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
                 public void write(OutputStream os) throws IOException {
                     os.write("after".getBytes(StandardCharsets.US_ASCII));
                     os.flush();
-                    assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
+                    assertTrue(tmp.exists(), "implementation of AtomicFileOutputStream has changed, update the test");
                     throw new RuntimeException();
                 }
             });
         } catch (RuntimeException ex) {
             exception = true;
         }
-        assertFalse("tmp file should have been deleted", tmp.exists());
-        assertTrue("should have raised an exception", exception);
+        assertFalse(tmp.exists(), "tmp file should have been deleted");
+        assertTrue(exception, "should have raised an exception");
         // content preserved
         assertEquals("before", getContent(target));
         target.delete();
@@ -122,15 +122,15 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
                 public void write(Writer os) throws IOException {
                     os.write("after");
                     os.flush();
-                    assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
+                    assertTrue(tmp.exists(), "implementation of AtomicFileOutputStream has changed, update the test");
                     throw new RuntimeException();
                 }
             });
         } catch (RuntimeException ex) {
             exception = true;
         }
-        assertFalse("tmp file should have been deleted", tmp.exists());
-        assertTrue("should have raised an exception", exception);
+        assertFalse(tmp.exists(), "tmp file should have been deleted");
+        assertTrue(exception, "should have raised an exception");
         // content preserved
         assertEquals("before", getContent(target));
         target.delete();
@@ -149,15 +149,15 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
                 public void write(OutputStream os) throws IOException {
                     os.write("after".getBytes(StandardCharsets.US_ASCII));
                     os.flush();
-                    assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
+                    assertTrue(tmp.exists(), "implementation of AtomicFileOutputStream has changed, update the test");
                     throw new IOException();
                 }
             });
         } catch (IOException ex) {
             exception = true;
         }
-        assertFalse("tmp file should have been deleted", tmp.exists());
-        assertTrue("should have raised an exception", exception);
+        assertFalse(tmp.exists(), "tmp file should have been deleted");
+        assertTrue(exception, "should have raised an exception");
         // content preserved
         assertEquals("before", getContent(target));
         target.delete();
@@ -176,15 +176,15 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
                 public void write(Writer os) throws IOException {
                     os.write("after");
                     os.flush();
-                    assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
+                    assertTrue(tmp.exists(), "implementation of AtomicFileOutputStream has changed, update the test");
                     throw new IOException();
                 }
             });
         } catch (IOException ex) {
             exception = true;
         }
-        assertFalse("tmp file should have been deleted", tmp.exists());
-        assertTrue("should have raised an exception", exception);
+        assertFalse(tmp.exists(), "tmp file should have been deleted");
+        assertTrue(exception, "should have raised an exception");
         // content preserved
         assertEquals("before", getContent(target));
         target.delete();
@@ -203,15 +203,15 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
                 public void write(OutputStream os) throws IOException {
                     os.write("after".getBytes(StandardCharsets.US_ASCII));
                     os.flush();
-                    assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
+                    assertTrue(tmp.exists(), "implementation of AtomicFileOutputStream has changed, update the test");
                     throw new Error();
                 }
             });
         } catch (Error ex) {
             exception = true;
         }
-        assertFalse("tmp file should have been deleted", tmp.exists());
-        assertTrue("should have raised an exception", exception);
+        assertFalse(tmp.exists(), "tmp file should have been deleted");
+        assertTrue(exception, "should have raised an exception");
         // content preserved
         assertEquals("before", getContent(target));
         target.delete();
@@ -230,15 +230,15 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
                 public void write(Writer os) throws IOException {
                     os.write("after");
                     os.flush();
-                    assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
+                    assertTrue(tmp.exists(), "implementation of AtomicFileOutputStream has changed, update the test");
                     throw new Error();
                 }
             });
         } catch (Error ex) {
             exception = true;
         }
-        assertFalse("tmp file should have been deleted", tmp.exists());
-        assertTrue("should have raised an exception", exception);
+        assertFalse(tmp.exists(), "tmp file should have been deleted");
+        assertTrue(exception, "should have raised an exception");
         // content preserved
         assertEquals("before", getContent(target));
         target.delete();
@@ -251,12 +251,12 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
         File target = new File(tmpdir, "target.txt");
         final File tmp = new File(tmpdir, "target.txt.tmp");
         target.delete();
-        assertFalse("file should not exist", target.exists());
+        assertFalse(target.exists(), "file should not exist");
         new AtomicFileWritingIdiom(target, new OutputStreamStatement() {
             @Override
             public void write(OutputStream os) throws IOException {
                 os.write("after".getBytes(StandardCharsets.US_ASCII));
-                assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
+                assertTrue(tmp.exists(), "implementation of AtomicFileOutputStream has changed, update the test");
             }
         });
         // content changed
@@ -269,15 +269,15 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
         File target = new File(tmpdir, "target.txt");
         final File tmp = new File(tmpdir, "target.txt.tmp");
         target.delete();
-        assertFalse("file should not exist", target.exists());
+        assertFalse(target.exists(), "file should not exist");
         new AtomicFileWritingIdiom(target, new WriterStatement() {
             @Override
             public void write(Writer os) throws IOException {
                 os.write("after");
-                assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
+                assertTrue(tmp.exists(), "implementation of AtomicFileOutputStream has changed, update the test");
             }
         });
-        assertFalse("tmp file should have been deleted", tmp.exists());
+        assertFalse(tmp.exists(), "tmp file should have been deleted");
         // content changed
         assertEquals("after", getContent(target));
         target.delete();
@@ -288,7 +288,7 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
         File target = new File(tmpdir, "target.txt");
         final File tmp = new File(tmpdir, "target.txt.tmp");
         target.delete();
-        assertFalse("file should not exist", target.exists());
+        assertFalse(target.exists(), "file should not exist");
         boolean exception = false;
         try {
             new AtomicFileWritingIdiom(target, new OutputStreamStatement() {
@@ -296,17 +296,17 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
                 public void write(OutputStream os) throws IOException {
                     os.write("after".getBytes(StandardCharsets.US_ASCII));
                     os.flush();
-                    assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
+                    assertTrue(tmp.exists(), "implementation of AtomicFileOutputStream has changed, update the test");
                     throw new RuntimeException();
                 }
             });
         } catch (RuntimeException ex) {
             exception = true;
         }
-        assertFalse("tmp file should have been deleted", tmp.exists());
-        assertTrue("should have raised an exception", exception);
+        assertFalse(tmp.exists(), "tmp file should have been deleted");
+        assertTrue(exception, "should have raised an exception");
         // file should not exist
-        assertFalse("file should not exist", target.exists());
+        assertFalse(target.exists(), "file should not exist");
     }
 
     @Test
@@ -314,7 +314,7 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
         File target = new File(tmpdir, "target.txt");
         final File tmp = new File(tmpdir, "target.txt.tmp");
         target.delete();
-        assertFalse("file should not exist", target.exists());
+        assertFalse(target.exists(), "file should not exist");
         boolean exception = false;
         try {
             new AtomicFileWritingIdiom(target, new WriterStatement() {
@@ -322,17 +322,17 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
                 public void write(Writer os) throws IOException {
                     os.write("after");
                     os.flush();
-                    assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
+                    assertTrue(tmp.exists(), "implementation of AtomicFileOutputStream has changed, update the test");
                     throw new RuntimeException();
                 }
             });
         } catch (RuntimeException ex) {
             exception = true;
         }
-        assertFalse("tmp file should have been deleted", tmp.exists());
-        assertTrue("should have raised an exception", exception);
+        assertFalse(tmp.exists(), "tmp file should have been deleted");
+        assertTrue(exception, "should have raised an exception");
         // file should not exist
-        assertFalse("file should not exist", target.exists());
+        assertFalse(target.exists(), "file should not exist");
     }
 
     private String getContent(File file, String encoding) throws IOException {

+ 35 - 13
zookeeper-server/src/test/java/org/apache/zookeeper/common/BaseX509ParameterizedTestCase.java

@@ -22,15 +22,16 @@ import java.io.File;
 import java.io.IOException;
 import java.security.Security;
 import java.util.ArrayList;
-import java.util.Collection;
 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.AfterClass;
-import org.junit.BeforeClass;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.params.provider.Arguments;
 
 /**
  * Base class for parameterized unit tests that use X509TestContext for testing
@@ -45,19 +46,20 @@ public abstract class BaseX509ParameterizedTestCase extends ZKTestCase {
     /**
      * Default parameters suitable for most subclasses. See example usage
      * in {@link X509UtilTest}.
-     * @return an array of parameter combinations to test with.
+     * @return a stream of parameter combinations to test with.
      */
-    public static Collection<Object[]> defaultParams() {
-        ArrayList<Object[]> result = new ArrayList<>();
+    public static Stream<Arguments> data() {
+        ArrayList<Arguments> result = new ArrayList<>();
         int paramIndex = 0;
         for (X509KeyType caKeyType : X509KeyType.values()) {
             for (X509KeyType certKeyType : X509KeyType.values()) {
                 for (String keyPassword : new String[]{"", "pa$$w0rd"}) {
-                    result.add(new Object[]{caKeyType, certKeyType, keyPassword, paramIndex++});
+                    result.add(Arguments.of(caKeyType, certKeyType, keyPassword, paramIndex++));
                 }
             }
         }
-        return result;
+
+        return result.stream();
     }
 
     /**
@@ -70,16 +72,16 @@ public abstract class BaseX509ParameterizedTestCase extends ZKTestCase {
 
     protected X509TestContext x509TestContext;
 
-    @BeforeClass
+    @BeforeAll
     public static void setUpBaseClass() throws Exception {
         Security.addProvider(new BouncyCastleProvider());
         cachedTestContexts = new HashMap<>();
         tempDir = ClientBase.createEmptyTestDir();
     }
 
-    @AfterClass
+    @AfterAll
     public static void cleanUpBaseClass() {
-        Security.removeProvider("BC");
+        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
         cachedTestContexts.clear();
         cachedTestContexts = null;
         try {
@@ -90,13 +92,13 @@ public abstract class BaseX509ParameterizedTestCase extends ZKTestCase {
     }
 
     /**
-     * Constructor. See example usage in {@link X509UtilTest}.
+     * Init method. See example usage in {@link X509UtilTest}.
      *
      * @param paramIndex the index under which the X509TestContext should be cached.
      * @param contextSupplier a function that creates and returns the X509TestContext
      *                        for the current index if one is not already cached.
      */
-    protected BaseX509ParameterizedTestCase(
+    protected void init(
             Integer paramIndex, java.util.function.Supplier<X509TestContext> contextSupplier) {
         if (cachedTestContexts.containsKey(paramIndex)) {
             x509TestContext = cachedTestContexts.get(paramIndex);
@@ -106,4 +108,24 @@ public abstract class BaseX509ParameterizedTestCase extends ZKTestCase {
         }
     }
 
+    protected void init(
+            final X509KeyType caKeyType,
+            final X509KeyType certKeyType,
+            final String keyPassword,
+            final Integer paramIndex)
+            throws Exception {
+        init(paramIndex, () -> {
+            try {
+                return X509TestContext.newBuilder()
+                        .setTempDir(tempDir)
+                        .setKeyStorePassword(keyPassword)
+                        .setKeyStoreKeyType(certKeyType)
+                        .setTrustStorePassword(keyPassword)
+                        .setTrustStoreKeyType(caKeyType)
+                        .build();
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+        });
+    }
 }

+ 9 - 9
zookeeper-server/src/test/java/org/apache/zookeeper/common/FileChangeWatcherTest.java

@@ -18,9 +18,9 @@
 
 package org.apache.zookeeper.common;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.File;
 import java.io.IOException;
 import java.nio.charset.StandardCharsets;
@@ -32,9 +32,9 @@ 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.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -47,14 +47,14 @@ public class FileChangeWatcherTest extends ZKTestCase {
 
     private static final long FS_TIMEOUT = 30000L;
 
-    @BeforeClass
+    @BeforeAll
     public static void createTempFile() throws IOException {
         tempDir = ClientBase.createEmptyTestDir();
         tempFile = File.createTempFile("zk_test_", "", tempDir);
         tempFile.deleteOnExit();
     }
 
-    @AfterClass
+    @AfterAll
     public static void cleanupTempDir() {
         try {
             FileUtils.deleteDirectory(tempDir);
@@ -91,7 +91,7 @@ public class FileChangeWatcherTest extends ZKTestCase {
                     if (events.size() < i + 1) {
                         events.wait(FS_TIMEOUT);
                     }
-                    assertEquals("Wrong number of events", i + 1, events.size());
+                    assertEquals(i + 1, events.size(), "Wrong number of events");
                     WatchEvent<?> event = events.get(i);
                     assertEquals(StandardWatchEventKinds.ENTRY_MODIFY, event.kind());
                     assertEquals(tempFile.getName(), event.context().toString());

+ 7 - 4
zookeeper-server/src/test/java/org/apache/zookeeper/common/FileKeyStoreLoaderBuilderProviderTest.java

@@ -18,9 +18,10 @@
 
 package org.apache.zookeeper.common;
 
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import org.apache.zookeeper.ZKTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class FileKeyStoreLoaderBuilderProviderTest extends ZKTestCase {
 
@@ -42,9 +43,11 @@ public class FileKeyStoreLoaderBuilderProviderTest extends ZKTestCase {
         assertTrue(builder instanceof PKCS12FileLoader.Builder);
     }
 
-    @Test(expected = NullPointerException.class)
+    @Test
     public void testGetBuilderForNullFileType() {
-        FileKeyStoreLoaderBuilderProvider.getBuilderForKeyStoreFileType(null);
+        assertThrows(NullPointerException.class, () -> {
+            FileKeyStoreLoaderBuilderProvider.getBuilderForKeyStoreFileType(null);
+        });
     }
 
 }

+ 98 - 60
zookeeper-server/src/test/java/org/apache/zookeeper/common/JKSFileLoaderTest.java

@@ -18,95 +18,133 @@
 
 package org.apache.zookeeper.common;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import java.io.IOException;
 import java.security.KeyStore;
-import java.util.Collection;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
 
-@RunWith(Parameterized.class)
 public class JKSFileLoaderTest extends BaseX509ParameterizedTestCase {
 
-    @Parameterized.Parameters
-    public static Collection<Object[]> params() {
-        return BaseX509ParameterizedTestCase.defaultParams();
-    }
-
-    public JKSFileLoaderTest(
-            final X509KeyType caKeyType, final X509KeyType certKeyType, final String keyPassword, final Integer paramIndex) {
-        super(paramIndex, () -> {
-            try {
-                return X509TestContext.newBuilder().setTempDir(tempDir).setKeyStorePassword(keyPassword).setKeyStoreKeyType(certKeyType).setTrustStorePassword(keyPassword).setTrustStoreKeyType(caKeyType).build();
-            } catch (Exception e) {
-                throw new RuntimeException(e);
-            }
-        });
-    }
-
-    @Test
-    public void testLoadKeyStore() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadKeyStore(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
         KeyStore ks = new JKSFileLoader.Builder().setKeyStorePath(path).setKeyStorePassword(x509TestContext.getKeyStorePassword()).build().loadKeyStore();
         assertEquals(1, ks.size());
     }
 
-    @Test(expected = Exception.class)
-    public void testLoadKeyStoreWithWrongPassword() throws Exception {
-        String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
-        new JKSFileLoader.Builder().setKeyStorePath(path).setKeyStorePassword("wrong password").build().loadKeyStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadKeyStoreWithWrongPassword(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(Exception.class, () -> {
+            String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
+            new JKSFileLoader.Builder().setKeyStorePath(path).setKeyStorePassword("wrong password").build().loadKeyStore();
+        });
     }
 
-    @Test(expected = IOException.class)
-    public void testLoadKeyStoreWithWrongFilePath() throws Exception {
-        String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
-        new JKSFileLoader.Builder().setKeyStorePath(path
-                                                            + ".does_not_exist").setKeyStorePassword(x509TestContext.getKeyStorePassword()).build().loadKeyStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadKeyStoreWithWrongFilePath(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(IOException.class, () -> {
+            String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
+            new JKSFileLoader.Builder().setKeyStorePath(path
+                    + ".does_not_exist").setKeyStorePassword(x509TestContext.getKeyStorePassword()).build().loadKeyStore();
+        });
     }
 
-    @Test(expected = NullPointerException.class)
-    public void testLoadKeyStoreWithNullFilePath() throws Exception {
-        new JKSFileLoader.Builder().setKeyStorePassword(x509TestContext.getKeyStorePassword()).build().loadKeyStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadKeyStoreWithNullFilePath(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(NullPointerException.class, () -> {
+            new JKSFileLoader.Builder().setKeyStorePassword(x509TestContext.getKeyStorePassword()).build().loadKeyStore();
+        });
     }
 
-    @Test(expected = IOException.class)
-    public void testLoadKeyStoreWithWrongFileType() throws Exception {
-        // Trying to load a PEM file with JKS loader should fail
-        String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
-        new JKSFileLoader.Builder().setKeyStorePath(path).setKeyStorePassword(x509TestContext.getKeyStorePassword()).build().loadKeyStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadKeyStoreWithWrongFileType(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(IOException.class, () -> {
+            // Trying to load a PEM file with JKS loader should fail
+            String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
+            new JKSFileLoader.Builder().setKeyStorePath(path).setKeyStorePassword(x509TestContext.getKeyStorePassword()).build().loadKeyStore();
+        });
     }
 
-    @Test
-    public void testLoadTrustStore() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadTrustStore(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
         KeyStore ts = new JKSFileLoader.Builder().setTrustStorePath(path).setTrustStorePassword(x509TestContext.getTrustStorePassword()).build().loadTrustStore();
         assertEquals(1, ts.size());
     }
 
-    @Test(expected = Exception.class)
-    public void testLoadTrustStoreWithWrongPassword() throws Exception {
-        String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
-        new JKSFileLoader.Builder().setTrustStorePath(path).setTrustStorePassword("wrong password").build().loadTrustStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadTrustStoreWithWrongPassword(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(Exception.class, () -> {
+            String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
+            new JKSFileLoader.Builder().setTrustStorePath(path).setTrustStorePassword("wrong password").build().loadTrustStore();
+        });
     }
 
-    @Test(expected = IOException.class)
-    public void testLoadTrustStoreWithWrongFilePath() throws Exception {
-        String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
-        new JKSFileLoader.Builder().setTrustStorePath(path
-                                                              + ".does_not_exist").setTrustStorePassword(x509TestContext.getTrustStorePassword()).build().loadTrustStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadTrustStoreWithWrongFilePath(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(IOException.class, () -> {
+            String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
+            new JKSFileLoader.Builder().setTrustStorePath(path
+                    + ".does_not_exist").setTrustStorePassword(x509TestContext.getTrustStorePassword()).build().loadTrustStore();
+        });
     }
 
-    @Test(expected = NullPointerException.class)
-    public void testLoadTrustStoreWithNullFilePath() throws Exception {
-        new JKSFileLoader.Builder().setTrustStorePassword(x509TestContext.getTrustStorePassword()).build().loadTrustStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadTrustStoreWithNullFilePath(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(NullPointerException.class, () -> {
+            new JKSFileLoader.Builder().setTrustStorePassword(x509TestContext.getTrustStorePassword()).build().loadTrustStore();
+        });
     }
 
-    @Test(expected = IOException.class)
-    public void testLoadTrustStoreWithWrongFileType() throws Exception {
-        // Trying to load a PEM file with JKS loader should fail
-        String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
-        new JKSFileLoader.Builder().setTrustStorePath(path).setTrustStorePassword(x509TestContext.getTrustStorePassword()).build().loadTrustStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadTrustStoreWithWrongFileType(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(IOException.class, () -> {
+            // Trying to load a PEM file with JKS loader should fail
+            String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
+            new JKSFileLoader.Builder().setTrustStorePath(path).setTrustStorePassword(x509TestContext.getTrustStorePassword()).build().loadTrustStore();
+        });
     }
 
 }

+ 20 - 11
zookeeper-server/src/test/java/org/apache/zookeeper/common/KeyStoreFileTypeTest.java

@@ -18,10 +18,11 @@
 
 package org.apache.zookeeper.common;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import org.apache.zookeeper.ZKTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class KeyStoreFileTypeTest extends ZKTestCase {
 
@@ -50,9 +51,11 @@ public class KeyStoreFileTypeTest extends ZKTestCase {
         assertNull(KeyStoreFileType.fromPropertyValue(null));
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testFromPropertyValueThrowsOnBadPropertyValue() {
-        KeyStoreFileType.fromPropertyValue("foobar");
+        assertThrows(IllegalArgumentException.class, () -> {
+            KeyStoreFileType.fromPropertyValue("foobar");
+        });
     }
 
     @Test
@@ -65,9 +68,11 @@ public class KeyStoreFileTypeTest extends ZKTestCase {
         assertEquals(KeyStoreFileType.PKCS12, KeyStoreFileType.fromFilename("/path/to/key/dir/mykey.p12"));
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testFromFilenameThrowsOnBadFileExtension() {
-        KeyStoreFileType.fromFilename("prod.key");
+        assertThrows(IllegalArgumentException.class, () -> {
+            KeyStoreFileType.fromFilename("prod.key");
+        });
     }
 
     @Test
@@ -80,14 +85,18 @@ public class KeyStoreFileTypeTest extends ZKTestCase {
         assertEquals(KeyStoreFileType.JKS, KeyStoreFileType.fromPropertyValueOrFileName("", "prod.jks"));
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testFromPropertyValueOrFileNameThrowsOnBadPropertyValue() {
-        KeyStoreFileType.fromPropertyValueOrFileName("foobar", "prod.jks");
+        assertThrows(IllegalArgumentException.class, () -> {
+            KeyStoreFileType.fromPropertyValueOrFileName("foobar", "prod.jks");
+        });
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testFromPropertyValueOrFileNameThrowsOnBadFileExtension() {
-        KeyStoreFileType.fromPropertyValueOrFileName("", "prod.key");
+        assertThrows(IllegalArgumentException.class, () -> {
+            KeyStoreFileType.fromPropertyValueOrFileName("", "prod.key");
+        });
     }
 
 }

+ 20 - 11
zookeeper-server/src/test/java/org/apache/zookeeper/common/NetUtilsTest.java

@@ -20,11 +20,12 @@ package org.apache.zookeeper.common;
 
 import static org.hamcrest.CoreMatchers.anyOf;
 import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import java.net.InetSocketAddress;
 import org.apache.zookeeper.ZKTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class NetUtilsTest extends ZKTestCase {
 
@@ -69,24 +70,32 @@ public class NetUtilsTest extends ZKTestCase {
         assertEquals("doesnt.exist.com:1234", NetUtils.formatInetAddr(isa));
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void tetGetIPV6HostAndPort_WhenHostDoesNotEndWithBracket() {
-        NetUtils.getIPV6HostAndPort("[2001:0db8:85a3:0000:0000:8a2e:0370:7334:443");
+        assertThrows(IllegalArgumentException.class, () -> {
+            NetUtils.getIPV6HostAndPort("[2001:0db8:85a3:0000:0000:8a2e:0370:7334:443");
+        });
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void tetGetIPV6HostAndPort_WhenNoPortAfterColon() {
-        NetUtils.getIPV6HostAndPort("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:");
+        assertThrows(IllegalArgumentException.class, () -> {
+            NetUtils.getIPV6HostAndPort("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:");
+        });
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void tetGetIPV6HostAndPort_WhenPortIsNotSeparatedProperly() {
-        NetUtils.getIPV6HostAndPort("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]2181");
+        assertThrows(IllegalArgumentException.class, () -> {
+            NetUtils.getIPV6HostAndPort("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]2181");
+        });
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void tetGetIPV6HostAndPort_WhenHostIsEmpty() {
-        NetUtils.getIPV6HostAndPort("[]:2181");
+        assertThrows(IllegalArgumentException.class, () -> {
+            NetUtils.getIPV6HostAndPort("[]:2181");
+        });
     }
 
     @Test

+ 103 - 82
zookeeper-server/src/test/java/org/apache/zookeeper/common/PEMFileLoaderTest.java

@@ -18,45 +18,22 @@
 
 package org.apache.zookeeper.common;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import java.io.IOException;
 import java.security.KeyStore;
 import java.security.KeyStoreException;
-import java.util.Collection;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
 
-@RunWith(Parameterized.class)
 public class PEMFileLoaderTest extends BaseX509ParameterizedTestCase {
 
-    @Parameterized.Parameters
-    public static Collection<Object[]> params() {
-        return BaseX509ParameterizedTestCase.defaultParams();
-    }
-
-    public PEMFileLoaderTest(
-        final X509KeyType caKeyType,
-        final X509KeyType certKeyType,
-        final String keyPassword,
-        final Integer paramIndex) {
-        super(paramIndex, () -> {
-            try {
-                return X509TestContext.newBuilder()
-                                      .setTempDir(tempDir)
-                                      .setKeyStorePassword(keyPassword)
-                                      .setKeyStoreKeyType(certKeyType)
-                                      .setTrustStorePassword(keyPassword)
-                                      .setTrustStoreKeyType(caKeyType)
-                                      .build();
-            } catch (Exception e) {
-                throw new RuntimeException(e);
-            }
-        });
-    }
-
-    @Test
-    public void testLoadKeyStore() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadKeyStore(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
         KeyStore ks = new PEMFileLoader.Builder()
             .setKeyStorePath(path)
@@ -66,47 +43,75 @@ public class PEMFileLoaderTest extends BaseX509ParameterizedTestCase {
         assertEquals(1, ks.size());
     }
 
-    @Test(expected = Exception.class)
-    public void testLoadKeyStoreWithWrongPassword() throws Exception {
-        String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
-        new PEMFileLoader.Builder()
-            .setKeyStorePath(path)
-            .setKeyStorePassword("wrong password")
-            .build()
-            .loadKeyStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadKeyStoreWithWrongPassword(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(Exception.class, () -> {
+            String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
+            new PEMFileLoader.Builder()
+                    .setKeyStorePath(path)
+                    .setKeyStorePassword("wrong password")
+                    .build()
+                    .loadKeyStore();
+        });
     }
 
-    @Test(expected = IOException.class)
-    public void testLoadKeyStoreWithWrongFilePath() throws Exception {
-        String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
-        new PEMFileLoader.Builder()
-            .setKeyStorePath(path + ".does_not_exist")
-            .setKeyStorePassword(x509TestContext.getKeyStorePassword())
-            .build()
-            .loadKeyStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadKeyStoreWithWrongFilePath(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(IOException.class, () -> {
+            String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
+            new PEMFileLoader.Builder()
+                    .setKeyStorePath(path + ".does_not_exist")
+                    .setKeyStorePassword(x509TestContext.getKeyStorePassword())
+                    .build()
+                    .loadKeyStore();
+        });
     }
 
-    @Test(expected = NullPointerException.class)
-    public void testLoadKeyStoreWithNullFilePath() throws Exception {
-        new PEMFileLoader.Builder()
-            .setKeyStorePassword(x509TestContext.getKeyStorePassword())
-            .build()
-            .loadKeyStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadKeyStoreWithNullFilePath(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(NullPointerException.class, () -> {
+            new PEMFileLoader.Builder()
+                    .setKeyStorePassword(x509TestContext.getKeyStorePassword())
+                    .build()
+                    .loadKeyStore();
+        });
     }
 
-    @Test(expected = KeyStoreException.class)
-    public void testLoadKeyStoreWithWrongFileType() throws Exception {
-        // Trying to load a JKS file with PEM loader should fail
-        String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
-        new PEMFileLoader.Builder()
-            .setKeyStorePath(path)
-            .setKeyStorePassword(x509TestContext.getKeyStorePassword())
-            .build()
-            .loadKeyStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadKeyStoreWithWrongFileType(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(KeyStoreException.class, () -> {
+            // Trying to load a JKS file with PEM loader should fail
+            String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
+            new PEMFileLoader.Builder()
+                    .setKeyStorePath(path)
+                    .setKeyStorePassword(x509TestContext.getKeyStorePassword())
+                    .build()
+                    .loadKeyStore();
+        });
     }
 
-    @Test
-    public void testLoadTrustStore() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadTrustStore(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
         KeyStore ts = new PEMFileLoader.Builder()
             .setTrustStorePath(path)
@@ -116,26 +121,42 @@ public class PEMFileLoaderTest extends BaseX509ParameterizedTestCase {
         assertEquals(1, ts.size());
     }
 
-    @Test(expected = IOException.class)
-    public void testLoadTrustStoreWithWrongFilePath() throws Exception {
-        String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
-        new PEMFileLoader.Builder()
-            .setTrustStorePath(path + ".does_not_exist")
-            .setTrustStorePassword(x509TestContext.getTrustStorePassword())
-            .build()
-            .loadTrustStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadTrustStoreWithWrongFilePath(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(IOException.class, () -> {
+            String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
+            new PEMFileLoader.Builder()
+                    .setTrustStorePath(path + ".does_not_exist")
+                    .setTrustStorePassword(x509TestContext.getTrustStorePassword())
+                    .build()
+                    .loadTrustStore();
+        });
     }
 
-    @Test(expected = NullPointerException.class)
-    public void testLoadTrustStoreWithNullFilePath() throws Exception {
-        new PEMFileLoader.Builder()
-            .setTrustStorePassword(x509TestContext.getTrustStorePassword())
-            .build()
-            .loadTrustStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadTrustStoreWithNullFilePath(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(NullPointerException.class, () -> {
+            new PEMFileLoader.Builder()
+                    .setTrustStorePassword(x509TestContext.getTrustStorePassword())
+                    .build()
+                    .loadTrustStore();
+        });
     }
 
-    @Test
-    public void testLoadTrustStoreWithWrongFileType() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadTrustStoreWithWrongFileType(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         // Trying to load a JKS file with PEM loader should fail
         String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
         KeyStore ts = new PEMFileLoader.Builder()

+ 126 - 97
zookeeper-server/src/test/java/org/apache/zookeeper/common/PKCS12FileLoaderTest.java

@@ -18,44 +18,21 @@
 
 package org.apache.zookeeper.common;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import java.io.IOException;
 import java.security.KeyStore;
-import java.util.Collection;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
 
-@RunWith(Parameterized.class)
 public class PKCS12FileLoaderTest extends BaseX509ParameterizedTestCase {
 
-    @Parameterized.Parameters
-    public static Collection<Object[]> params() {
-        return BaseX509ParameterizedTestCase.defaultParams();
-    }
-
-    public PKCS12FileLoaderTest(
-        final X509KeyType caKeyType,
-        final X509KeyType certKeyType,
-        final String keyPassword,
-        final Integer paramIndex) {
-        super(paramIndex, () -> {
-            try {
-                return X509TestContext.newBuilder()
-                                      .setTempDir(tempDir)
-                                      .setKeyStorePassword(keyPassword)
-                                      .setKeyStoreKeyType(certKeyType)
-                                      .setTrustStorePassword(keyPassword)
-                                      .setTrustStoreKeyType(caKeyType)
-                                      .build();
-            } catch (Exception e) {
-                throw new RuntimeException(e);
-            }
-        });
-    }
-
-    @Test
-    public void testLoadKeyStore() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadKeyStore(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath();
         KeyStore ks = new PKCS12FileLoader.Builder()
             .setKeyStorePath(path)
@@ -65,47 +42,75 @@ public class PKCS12FileLoaderTest extends BaseX509ParameterizedTestCase {
         assertEquals(1, ks.size());
     }
 
-    @Test(expected = Exception.class)
-    public void testLoadKeyStoreWithWrongPassword() throws Exception {
-        String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath();
-        new PKCS12FileLoader.Builder()
-            .setKeyStorePath(path)
-            .setKeyStorePassword("wrong password")
-            .build()
-            .loadKeyStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadKeyStoreWithWrongPassword(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(Exception.class, () -> {
+            String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath();
+            new PKCS12FileLoader.Builder()
+                    .setKeyStorePath(path)
+                    .setKeyStorePassword("wrong password")
+                    .build()
+                    .loadKeyStore();
+        });
     }
 
-    @Test(expected = IOException.class)
-    public void testLoadKeyStoreWithWrongFilePath() throws Exception {
-        String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath();
-        new PKCS12FileLoader.Builder()
-            .setKeyStorePath(path + ".does_not_exist")
-            .setKeyStorePassword(x509TestContext.getKeyStorePassword())
-            .build()
-            .loadKeyStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadKeyStoreWithWrongFilePath(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(IOException.class, () -> {
+            String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath();
+            new PKCS12FileLoader.Builder()
+                    .setKeyStorePath(path + ".does_not_exist")
+                    .setKeyStorePassword(x509TestContext.getKeyStorePassword())
+                    .build()
+                    .loadKeyStore();
+        });
     }
 
-    @Test(expected = NullPointerException.class)
-    public void testLoadKeyStoreWithNullFilePath() throws Exception {
-        new PKCS12FileLoader.Builder()
-            .setKeyStorePassword(x509TestContext.getKeyStorePassword())
-            .build()
-            .loadKeyStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadKeyStoreWithNullFilePath(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(NullPointerException.class, () -> {
+            new PKCS12FileLoader.Builder()
+                    .setKeyStorePassword(x509TestContext.getKeyStorePassword())
+                    .build()
+                    .loadKeyStore();
+        });
     }
 
-    @Test(expected = IOException.class)
-    public void testLoadKeyStoreWithWrongFileType() throws Exception {
-        // Trying to load a PEM file with PKCS12 loader should fail
-        String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
-        new PKCS12FileLoader.Builder()
-            .setKeyStorePath(path)
-            .setKeyStorePassword(x509TestContext.getKeyStorePassword())
-            .build()
-            .loadKeyStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadKeyStoreWithWrongFileType(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(IOException.class, () -> {
+            // Trying to load a PEM file with PKCS12 loader should fail
+            String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
+            new PKCS12FileLoader.Builder()
+                    .setKeyStorePath(path)
+                    .setKeyStorePassword(x509TestContext.getKeyStorePassword())
+                    .build()
+                    .loadKeyStore();
+        });
     }
 
-    @Test
-    public void testLoadTrustStore() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadTrustStore(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath();
         KeyStore ts = new PKCS12FileLoader.Builder()
             .setTrustStorePath(path)
@@ -115,43 +120,67 @@ public class PKCS12FileLoaderTest extends BaseX509ParameterizedTestCase {
         assertEquals(1, ts.size());
     }
 
-    @Test(expected = Exception.class)
-    public void testLoadTrustStoreWithWrongPassword() throws Exception {
-        String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath();
-        new PKCS12FileLoader.Builder()
-            .setTrustStorePath(path)
-            .setTrustStorePassword("wrong password")
-            .build()
-            .loadTrustStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadTrustStoreWithWrongPassword(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(Exception.class, () -> {
+            String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath();
+            new PKCS12FileLoader.Builder()
+                    .setTrustStorePath(path)
+                    .setTrustStorePassword("wrong password")
+                    .build()
+                    .loadTrustStore();
+        });
     }
 
-    @Test(expected = IOException.class)
-    public void testLoadTrustStoreWithWrongFilePath() throws Exception {
-        String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath();
-        new PKCS12FileLoader.Builder()
-            .setTrustStorePath(path + ".does_not_exist")
-            .setTrustStorePassword(x509TestContext.getTrustStorePassword())
-            .build()
-            .loadTrustStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadTrustStoreWithWrongFilePath(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(IOException.class, () -> {
+            String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath();
+            new PKCS12FileLoader.Builder()
+                    .setTrustStorePath(path + ".does_not_exist")
+                    .setTrustStorePassword(x509TestContext.getTrustStorePassword())
+                    .build()
+                    .loadTrustStore();
+        });
     }
 
-    @Test(expected = NullPointerException.class)
-    public void testLoadTrustStoreWithNullFilePath() throws Exception {
-        new PKCS12FileLoader.Builder()
-            .setTrustStorePassword(x509TestContext.getTrustStorePassword())
-            .build()
-            .loadTrustStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadTrustStoreWithNullFilePath(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(NullPointerException.class, () -> {
+            new PKCS12FileLoader.Builder()
+                    .setTrustStorePassword(x509TestContext.getTrustStorePassword())
+                    .build()
+                    .loadTrustStore();
+        });
     }
 
-    @Test(expected = IOException.class)
-    public void testLoadTrustStoreWithWrongFileType() throws Exception {
-        // Trying to load a PEM file with PKCS12 loader should fail
-        String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
-        new PKCS12FileLoader.Builder()
-            .setTrustStorePath(path)
-            .setTrustStorePassword(x509TestContext.getTrustStorePassword())
-            .build()
-            .loadTrustStore();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadTrustStoreWithWrongFileType(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(IOException.class, () -> {
+            // Trying to load a PEM file with PKCS12 loader should fail
+            String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
+            new PKCS12FileLoader.Builder()
+                    .setTrustStorePath(path)
+                    .setTrustStorePassword(x509TestContext.getTrustStorePassword())
+                    .build()
+                    .loadTrustStore();
+        });
     }
 
 }

+ 27 - 16
zookeeper-server/src/test/java/org/apache/zookeeper/common/PathTrieTest.java

@@ -18,29 +18,34 @@
 
 package org.apache.zookeeper.common;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class PathTrieTest {
 
     private PathTrie pathTrie;
 
-    @Before
+    @BeforeEach
     public void before() {
         this.pathTrie = new PathTrie();
     }
 
-    @Test(expected = NullPointerException.class)
+    @Test
     public void addNullPath() {
-        this.pathTrie.addPath(null);
+        assertThrows(NullPointerException.class, () -> {
+            this.pathTrie.addPath(null);
+        });
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void addIllegalPath() {
-        this.pathTrie.addPath("");
+        assertThrows(IllegalArgumentException.class, () -> {
+            this.pathTrie.addPath("");
+        });
     }
 
     @Test
@@ -59,14 +64,18 @@ public class PathTrieTest {
         assertTrue(this.pathTrie.existsNode("/node1/node3"));
     }
 
-    @Test(expected = NullPointerException.class)
+    @Test
     public void deleteNullPath() {
-        this.pathTrie.deletePath(null);
+        assertThrows(NullPointerException.class, () -> {
+            this.pathTrie.deletePath(null);
+        });
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void deleteIllegalPath() {
-        this.pathTrie.deletePath("");
+        assertThrows(IllegalArgumentException.class, () -> {
+            this.pathTrie.deletePath("");
+        });
     }
 
     @Test
@@ -122,9 +131,11 @@ public class PathTrieTest {
         assertTrue(this.pathTrie.existsNode("/node1/node3"));
     }
 
-    @Test(expected = NullPointerException.class)
+    @Test
     public void findMaxPrefixNullPath() {
-        this.pathTrie.findMaxPrefix(null);
+        assertThrows(NullPointerException.class, () -> {
+            this.pathTrie.findMaxPrefix(null);
+        });
     }
 
     @Test

+ 62 - 31
zookeeper-server/src/test/java/org/apache/zookeeper/common/PathUtilsTest.java

@@ -18,8 +18,9 @@
 
 package org.apache.zookeeper.common;
 
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import org.apache.zookeeper.ZKTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class PathUtilsTest extends ZKTestCase {
 
@@ -28,44 +29,60 @@ public class PathUtilsTest extends ZKTestCase {
         PathUtils.validatePath("/this is / a valid/path");
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testValidatePath_Null() {
-        PathUtils.validatePath(null);
+        assertThrows(IllegalArgumentException.class, () -> {
+            PathUtils.validatePath(null);
+        });
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testValidatePath_EmptyString() {
-        PathUtils.validatePath("");
+        assertThrows(IllegalArgumentException.class, () -> {
+            PathUtils.validatePath("");
+        });
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testValidatePath_NotAbsolutePath() {
-        PathUtils.validatePath("not/valid");
+        assertThrows(IllegalArgumentException.class, () -> {
+            PathUtils.validatePath("not/valid");
+        });
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testValidatePath_EndsWithSlash() {
-        PathUtils.validatePath("/ends/with/slash/");
+        assertThrows(IllegalArgumentException.class, () -> {
+            PathUtils.validatePath("/ends/with/slash/");
+        });
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testValidatePath_ContainsNullCharacter() {
-        PathUtils.validatePath("/test\u0000");
+        assertThrows(IllegalArgumentException.class, () -> {
+            PathUtils.validatePath("/test\u0000");
+        });
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testValidatePath_DoubleSlash() {
-        PathUtils.validatePath("/double//slash");
+        assertThrows(IllegalArgumentException.class, () -> {
+            PathUtils.validatePath("/double//slash");
+        });
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testValidatePath_SinglePeriod() {
-        PathUtils.validatePath("/single/./period");
+        assertThrows(IllegalArgumentException.class, () -> {
+            PathUtils.validatePath("/single/./period");
+        });
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testValidatePath_DoublePeriod() {
-        PathUtils.validatePath("/double/../period");
+        assertThrows(IllegalArgumentException.class, () -> {
+            PathUtils.validatePath("/double/../period");
+        });
     }
 
     @Test
@@ -74,14 +91,18 @@ public class PathUtilsTest extends ZKTestCase {
         PathUtils.validatePath("/name/with.period.");
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testValidatePath_0x01() {
-        PathUtils.validatePath("/test\u0001");
+        assertThrows(IllegalArgumentException.class, () -> {
+            PathUtils.validatePath("/test\u0001");
+        });
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testValidatePath_0x1F() {
-        PathUtils.validatePath("/test\u001F");
+        assertThrows(IllegalArgumentException.class, () -> {
+            PathUtils.validatePath("/test\u001F");
+        });
     }
 
     @Test // The first allowable character
@@ -95,24 +116,32 @@ public class PathUtilsTest extends ZKTestCase {
         PathUtils.validatePath("/test\u007e");
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testValidatePath_0x7f() {
-        PathUtils.validatePath("/test\u007f");
+        assertThrows(IllegalArgumentException.class, () -> {
+            PathUtils.validatePath("/test\u007f");
+        });
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testValidatePath_0x9f() {
-        PathUtils.validatePath("/test\u009f");
+        assertThrows(IllegalArgumentException.class, () -> {
+            PathUtils.validatePath("/test\u009f");
+        });
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testValidatePath_ud800() {
-        PathUtils.validatePath("/test\ud800");
+        assertThrows(IllegalArgumentException.class, () -> {
+            PathUtils.validatePath("/test\ud800");
+        });
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testValidatePath_uf8ff() {
-        PathUtils.validatePath("/test\uf8ff");
+        assertThrows(IllegalArgumentException.class, () -> {
+            PathUtils.validatePath("/test\uf8ff");
+        });
     }
 
     @Test
@@ -120,9 +149,11 @@ public class PathUtilsTest extends ZKTestCase {
         PathUtils.validatePath("/test\uffef");
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testValidatePath_SupplementaryChar() {
-        PathUtils.validatePath("/test\ufff0");
+        assertThrows(IllegalArgumentException.class, () -> {
+            PathUtils.validatePath("/test\ufff0");
+        });
     }
 
 }

+ 2 - 2
zookeeper-server/src/test/java/org/apache/zookeeper/common/TimeTest.java

@@ -18,7 +18,7 @@
 
 package org.apache.zookeeper.common;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import java.util.Calendar;
 import java.util.Date;
 import java.util.concurrent.atomic.AtomicInteger;
@@ -27,7 +27,7 @@ import org.apache.zookeeper.Watcher;
 import org.apache.zookeeper.ZooDefs;
 import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 /**
  * Command line program for demonstrating robustness to clock

+ 401 - 218
zookeeper-server/src/test/java/org/apache/zookeeper/common/X509UtilTest.java

@@ -18,10 +18,11 @@
 
 package org.apache.zookeeper.common;
 
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.IOException;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
@@ -29,7 +30,6 @@ import java.net.ServerSocket;
 import java.net.Socket;
 import java.security.NoSuchAlgorithmException;
 import java.security.Security;
-import java.util.Collection;
 import java.util.concurrent.Callable;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.ExecutionException;
@@ -50,13 +50,11 @@ import javax.net.ssl.X509TrustManager;
 import org.apache.zookeeper.PortAssignment;
 import org.apache.zookeeper.client.ZKClientConfig;
 import org.apache.zookeeper.server.ServerCnxnFactory;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
 
-@RunWith(Parameterized.class)
 public class X509UtilTest extends BaseX509ParameterizedTestCase {
 
     private X509Util x509Util;
@@ -65,30 +63,10 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
         "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA"
     };
 
-    @Parameterized.Parameters
-    public static Collection<Object[]> params() {
-        return BaseX509ParameterizedTestCase.defaultParams();
-    }
-
-    public X509UtilTest(
-            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex) {
-        super(paramIndex, () -> {
-            try {
-                return X509TestContext.newBuilder()
-                                      .setTempDir(tempDir)
-                                      .setKeyStorePassword(keyPassword)
-                                      .setKeyStoreKeyType(certKeyType)
-                                      .setTrustStorePassword(keyPassword)
-                                      .setTrustStoreKeyType(caKeyType)
-                                      .build();
-            } catch (Exception e) {
-                throw new RuntimeException(e);
-            }
-        });
-    }
-
-    @Before
-    public void setUp() throws Exception {
+    public void init(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        super.init(caKeyType, certKeyType, keyPassword, paramIndex);
         try (X509Util x509util = new ClientX509Util()) {
             x509TestContext.setSystemProperties(x509util, KeyStoreFileType.JKS, KeyStoreFileType.JKS);
         }
@@ -97,7 +75,7 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
         x509Util = new ClientX509Util();
     }
 
-    @After
+    @AfterEach
     public void cleanUp() {
         x509TestContext.clearSystemProperties(x509Util);
         System.clearProperty(x509Util.getSslOcspEnabledProperty());
@@ -114,37 +92,64 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
         x509Util.close();
     }
 
-    @Test(timeout = 5000)
-    public void testCreateSSLContextWithoutCustomProtocol() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    @Timeout(value = 5)
+    public void testCreateSSLContextWithoutCustomProtocol(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         SSLContext sslContext = x509Util.getDefaultSSLContext();
         assertEquals(X509Util.DEFAULT_PROTOCOL, sslContext.getProtocol());
     }
 
-    @Test(timeout = 5000)
-    public void testCreateSSLContextWithCustomProtocol() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    @Timeout(value = 5)
+    public void testCreateSSLContextWithCustomProtocol(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
         final String protocol = "TLSv1.1";
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         System.setProperty(x509Util.getSslProtocolProperty(), protocol);
         SSLContext sslContext = x509Util.getDefaultSSLContext();
         assertEquals(protocol, sslContext.getProtocol());
     }
 
-    @Test(timeout = 5000)
-    public void testCreateSSLContextWithoutKeyStoreLocation() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    @Timeout(value = 5)
+    public void testCreateSSLContextWithoutKeyStoreLocation(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         System.clearProperty(x509Util.getSslKeystoreLocationProperty());
         x509Util.getDefaultSSLContext();
     }
 
-    @Test(timeout = 5000, expected = X509Exception.SSLContextException.class)
-    public void testCreateSSLContextWithoutKeyStorePassword() throws Exception {
-        if (!x509TestContext.isKeyStoreEncrypted()) {
-            throw new X509Exception.SSLContextException("");
-        }
-        System.clearProperty(x509Util.getSslKeystorePasswdProperty());
-        x509Util.getDefaultSSLContext();
+    @ParameterizedTest
+    @MethodSource("data")
+    @Timeout(value = 5)
+    public void testCreateSSLContextWithoutKeyStorePassword(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(X509Exception.SSLContextException.class, () -> {
+            if (!x509TestContext.isKeyStoreEncrypted()) {
+                throw new X509Exception.SSLContextException("");
+            }
+            System.clearProperty(x509Util.getSslKeystorePasswdProperty());
+            x509Util.getDefaultSSLContext();
+        });
     }
 
-    @Test(timeout = 5000)
-    public void testCreateSSLContextWithCustomCipherSuites() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    @Timeout(value = 5)
+    public void testCreateSSLContextWithCustomCipherSuites(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         setCustomCipherSuites();
         SSLSocket sslSocket = x509Util.createSSLSocket();
         assertArrayEquals(customCipherSuites, sslSocket.getEnabledCipherSuites());
@@ -152,8 +157,13 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
 
     // It would be great to test the value of PKIXBuilderParameters#setRevocationEnabled but it does not appear to be
     // possible
-    @Test(timeout = 5000)
-    public void testCRLEnabled() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    @Timeout(value = 5)
+    public void testCRLEnabled(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         System.setProperty(x509Util.getSslCrlEnabledProperty(), "true");
         x509Util.getDefaultSSLContext();
         assertTrue(Boolean.valueOf(System.getProperty("com.sun.net.ssl.checkRevocation")));
@@ -161,16 +171,26 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
         assertFalse(Boolean.valueOf(Security.getProperty("ocsp.enable")));
     }
 
-    @Test(timeout = 5000)
-    public void testCRLDisabled() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    @Timeout(value = 5)
+    public void testCRLDisabled(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         x509Util.getDefaultSSLContext();
         assertFalse(Boolean.valueOf(System.getProperty("com.sun.net.ssl.checkRevocation")));
         assertFalse(Boolean.valueOf(System.getProperty("com.sun.security.enableCRLDP")));
         assertFalse(Boolean.valueOf(Security.getProperty("ocsp.enable")));
     }
 
-    @Test(timeout = 5000)
-    public void testOCSPEnabled() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    @Timeout(value = 5)
+    public void testOCSPEnabled(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         System.setProperty(x509Util.getSslOcspEnabledProperty(), "true");
         x509Util.getDefaultSSLContext();
         assertTrue(Boolean.valueOf(System.getProperty("com.sun.net.ssl.checkRevocation")));
@@ -178,23 +198,38 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
         assertTrue(Boolean.valueOf(Security.getProperty("ocsp.enable")));
     }
 
-    @Test(timeout = 5000)
-    public void testCreateSSLSocket() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    @Timeout(value = 5)
+    public void testCreateSSLSocket(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         setCustomCipherSuites();
         SSLSocket sslSocket = x509Util.createSSLSocket();
         assertArrayEquals(customCipherSuites, sslSocket.getEnabledCipherSuites());
     }
 
-    @Test(timeout = 5000)
-    public void testCreateSSLServerSocketWithoutPort() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    @Timeout(value = 5)
+    public void testCreateSSLServerSocketWithoutPort(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         setCustomCipherSuites();
         SSLServerSocket sslServerSocket = x509Util.createSSLServerSocket();
         assertArrayEquals(customCipherSuites, sslServerSocket.getEnabledCipherSuites());
         assertTrue(sslServerSocket.getNeedClientAuth());
     }
 
-    @Test(timeout = 5000)
-    public void testCreateSSLServerSocketWithPort() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    @Timeout(value = 5)
+    public void testCreateSSLServerSocketWithPort(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         setCustomCipherSuites();
         int port = PortAssignment.unique();
         SSLServerSocket sslServerSocket = x509Util.createSSLServerSocket(port);
@@ -203,8 +238,12 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
         assertTrue(sslServerSocket.getNeedClientAuth());
     }
 
-    @Test
-    public void testLoadPEMKeyStore() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadPEMKeyStore(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         // Make sure we can instantiate a key manager from the PEM file on disk
         X509KeyManager km = X509Util.createKeyManager(
             x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
@@ -212,8 +251,12 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
             KeyStoreFileType.PEM.getPropertyValue());
     }
 
-    @Test
-    public void testLoadPEMKeyStoreNullPassword() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadPEMKeyStoreNullPassword(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         if (!x509TestContext.getKeyStorePassword().isEmpty()) {
             return;
         }
@@ -224,8 +267,12 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
             KeyStoreFileType.PEM.getPropertyValue());
     }
 
-    @Test
-    public void testLoadPEMKeyStoreAutodetectStoreFileType() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadPEMKeyStoreAutodetectStoreFileType(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         // Make sure we can instantiate a key manager from the PEM file on disk
         X509KeyManager km = X509Util.createKeyManager(
             x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
@@ -233,17 +280,27 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
             null /* null StoreFileType means 'autodetect from file extension' */);
     }
 
-    @Test(expected = X509Exception.KeyManagerException.class)
-    public void testLoadPEMKeyStoreWithWrongPassword() throws Exception {
-        // Attempting to load with the wrong key password should fail
-        X509KeyManager km = X509Util.createKeyManager(
-            x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
-            "wrong password", // intentionally use the wrong password
-            KeyStoreFileType.PEM.getPropertyValue());
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadPEMKeyStoreWithWrongPassword(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(X509Exception.KeyManagerException.class, () -> {
+            // Attempting to load with the wrong key password should fail
+            X509KeyManager km = X509Util.createKeyManager(
+                    x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
+                    "wrong password", // intentionally use the wrong password
+                    KeyStoreFileType.PEM.getPropertyValue());
+        });
     }
 
-    @Test
-    public void testLoadPEMTrustStore() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadPEMTrustStore(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         // Make sure we can instantiate a trust manager from the PEM file on disk
         X509TrustManager tm = X509Util.createTrustManager(
             x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
@@ -254,8 +311,12 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
             true);
     }
 
-    @Test
-    public void testLoadPEMTrustStoreNullPassword() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadPEMTrustStoreNullPassword(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         if (!x509TestContext.getTrustStorePassword().isEmpty()) {
             return;
         }
@@ -271,8 +332,12 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
 
     }
 
-    @Test
-    public void testLoadPEMTrustStoreAutodetectStoreFileType() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadPEMTrustStoreAutodetectStoreFileType(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         // Make sure we can instantiate a trust manager from the PEM file on disk
         X509TrustManager tm = X509Util.createTrustManager(
             x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
@@ -284,8 +349,12 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
             true);
     }
 
-    @Test
-    public void testLoadJKSKeyStore() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadJKSKeyStore(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         // Make sure we can instantiate a key manager from the JKS file on disk
         X509KeyManager km = X509Util.createKeyManager(
             x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
@@ -293,8 +362,12 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
             KeyStoreFileType.JKS.getPropertyValue());
     }
 
-    @Test
-    public void testLoadJKSKeyStoreNullPassword() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadJKSKeyStoreNullPassword(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         if (!x509TestContext.getKeyStorePassword().isEmpty()) {
             return;
         }
@@ -305,8 +378,12 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
             KeyStoreFileType.JKS.getPropertyValue());
     }
 
-    @Test
-    public void testLoadJKSKeyStoreAutodetectStoreFileType() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadJKSKeyStoreAutodetectStoreFileType(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         // Make sure we can instantiate a key manager from the JKS file on disk
         X509KeyManager km = X509Util.createKeyManager(
             x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
@@ -314,17 +391,27 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
             null /* null StoreFileType means 'autodetect from file extension' */);
     }
 
-    @Test(expected = X509Exception.KeyManagerException.class)
-    public void testLoadJKSKeyStoreWithWrongPassword() throws Exception {
-        // Attempting to load with the wrong key password should fail
-        X509KeyManager km = X509Util.createKeyManager(
-            x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
-            "wrong password",
-            KeyStoreFileType.JKS.getPropertyValue());
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadJKSKeyStoreWithWrongPassword(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(X509Exception.KeyManagerException.class, () -> {
+            // Attempting to load with the wrong key password should fail
+            X509KeyManager km = X509Util.createKeyManager(
+                    x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
+                    "wrong password",
+                    KeyStoreFileType.JKS.getPropertyValue());
+        });
     }
 
-    @Test
-    public void testLoadJKSTrustStore() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadJKSTrustStore(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         // Make sure we can instantiate a trust manager from the JKS file on disk
         X509TrustManager tm = X509Util.createTrustManager(
             x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
@@ -336,8 +423,12 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
             true);
     }
 
-    @Test
-    public void testLoadJKSTrustStoreNullPassword() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadJKSTrustStoreNullPassword(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         if (!x509TestContext.getTrustStorePassword().isEmpty()) {
             return;
         }
@@ -352,8 +443,12 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
             true);
     }
 
-    @Test
-    public void testLoadJKSTrustStoreAutodetectStoreFileType() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadJKSTrustStoreAutodetectStoreFileType(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         // Make sure we can instantiate a trust manager from the JKS file on disk
         X509TrustManager tm = X509Util.createTrustManager(
             x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
@@ -365,21 +460,31 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
             true);
     }
 
-    @Test(expected = X509Exception.TrustManagerException.class)
-    public void testLoadJKSTrustStoreWithWrongPassword() throws Exception {
-        // Attempting to load with the wrong key password should fail
-        X509TrustManager tm = X509Util.createTrustManager(
-            x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
-            "wrong password",
-            KeyStoreFileType.JKS.getPropertyValue(),
-            true,
-            true,
-            true,
-            true);
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadJKSTrustStoreWithWrongPassword(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(X509Exception.TrustManagerException.class, () -> {
+            // Attempting to load with the wrong key password should fail
+            X509TrustManager tm = X509Util.createTrustManager(
+                    x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
+                    "wrong password",
+                    KeyStoreFileType.JKS.getPropertyValue(),
+                    true,
+                    true,
+                    true,
+                    true);
+        });
     }
 
-    @Test
-    public void testLoadPKCS12KeyStore() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadPKCS12KeyStore(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         // Make sure we can instantiate a key manager from the PKCS12 file on disk
         X509KeyManager km = X509Util.createKeyManager(
             x509TestContext.getKeyStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath(),
@@ -387,8 +492,12 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
             KeyStoreFileType.PKCS12.getPropertyValue());
     }
 
-    @Test
-    public void testLoadPKCS12KeyStoreNullPassword() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadPKCS12KeyStoreNullPassword(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         if (!x509TestContext.getKeyStorePassword().isEmpty()) {
             return;
         }
@@ -399,8 +508,12 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
             KeyStoreFileType.PKCS12.getPropertyValue());
     }
 
-    @Test
-    public void testLoadPKCS12KeyStoreAutodetectStoreFileType() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadPKCS12KeyStoreAutodetectStoreFileType(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         // Make sure we can instantiate a key manager from the PKCS12 file on disk
         X509KeyManager km = X509Util.createKeyManager(
             x509TestContext.getKeyStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath(),
@@ -408,17 +521,27 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
             null /* null StoreFileType means 'autodetect from file extension' */);
     }
 
-    @Test(expected = X509Exception.KeyManagerException.class)
-    public void testLoadPKCS12KeyStoreWithWrongPassword() throws Exception {
-        // Attempting to load with the wrong key password should fail
-        X509KeyManager km = X509Util.createKeyManager(
-            x509TestContext.getKeyStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath(),
-            "wrong password",
-            KeyStoreFileType.PKCS12.getPropertyValue());
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadPKCS12KeyStoreWithWrongPassword(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(X509Exception.KeyManagerException.class, () -> {
+            // Attempting to load with the wrong key password should fail
+            X509KeyManager km = X509Util.createKeyManager(
+                    x509TestContext.getKeyStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath(),
+                    "wrong password",
+                    KeyStoreFileType.PKCS12.getPropertyValue());
+        });
     }
 
-    @Test
-    public void testLoadPKCS12TrustStore() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadPKCS12TrustStore(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         // Make sure we can instantiate a trust manager from the PKCS12 file on disk
         X509TrustManager tm = X509Util.createTrustManager(
             x509TestContext.getTrustStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath(),
@@ -429,8 +552,12 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
             true);
     }
 
-    @Test
-    public void testLoadPKCS12TrustStoreNullPassword() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadPKCS12TrustStoreNullPassword(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         if (!x509TestContext.getTrustStorePassword().isEmpty()) {
             return;
         }
@@ -445,8 +572,12 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
             true);
     }
 
-    @Test
-    public void testLoadPKCS12TrustStoreAutodetectStoreFileType() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadPKCS12TrustStoreAutodetectStoreFileType(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         // Make sure we can instantiate a trust manager from the PKCS12 file on disk
         X509TrustManager tm = X509Util.createTrustManager(
             x509TestContext.getTrustStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath(),
@@ -458,21 +589,31 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
             true);
     }
 
-    @Test(expected = X509Exception.TrustManagerException.class)
-    public void testLoadPKCS12TrustStoreWithWrongPassword() throws Exception {
-        // Attempting to load with the wrong key password should fail
-        X509TrustManager tm = X509Util.createTrustManager(
-            x509TestContext.getTrustStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath(),
-            "wrong password",
-            KeyStoreFileType.PKCS12.getPropertyValue(),
-            true,
-            true,
-            true,
-            true);
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testLoadPKCS12TrustStoreWithWrongPassword(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(X509Exception.TrustManagerException.class, () -> {
+            // Attempting to load with the wrong key password should fail
+            X509TrustManager tm = X509Util.createTrustManager(
+                    x509TestContext.getTrustStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath(),
+                    "wrong password",
+                    KeyStoreFileType.PKCS12.getPropertyValue(),
+                    true,
+                    true,
+                    true,
+                    true);
+        });
     }
 
-    @Test
-    public void testGetSslHandshakeDetectionTimeoutMillisProperty() {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testGetSslHandshakeDetectionTimeoutMillisProperty(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         assertEquals(X509Util.DEFAULT_HANDSHAKE_DETECTION_TIMEOUT_MILLIS, x509Util.getSslHandshakeTimeoutMillis());
         // Note: need to create a new ClientX509Util each time to pick up modified property value
         String newPropertyString = Integer.toString(X509Util.DEFAULT_HANDSHAKE_DETECTION_TIMEOUT_MILLIS + 1);
@@ -493,16 +634,26 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
         }
     }
 
-    @Test(expected = X509Exception.SSLContextException.class)
-    public void testCreateSSLContext_invalidCustomSSLContextClass() throws Exception {
-        ZKConfig zkConfig = new ZKConfig();
-        ClientX509Util clientX509Util = new ClientX509Util();
-        zkConfig.setProperty(clientX509Util.getSslContextSupplierClassProperty(), String.class.getCanonicalName());
-        clientX509Util.createSSLContext(zkConfig);
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testCreateSSLContext_invalidCustomSSLContextClass(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(X509Exception.SSLContextException.class, () -> {
+            ZKConfig zkConfig = new ZKConfig();
+            ClientX509Util clientX509Util = new ClientX509Util();
+            zkConfig.setProperty(clientX509Util.getSslContextSupplierClassProperty(), String.class.getCanonicalName());
+            clientX509Util.createSSLContext(zkConfig);
+        });
     }
 
-    @Test
-    public void testCreateSSLContext_validCustomSSLContextClass() throws Exception {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testCreateSSLContext_validCustomSSLContextClass(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         ZKConfig zkConfig = new ZKConfig();
         ClientX509Util clientX509Util = new ClientX509Util();
         zkConfig.setProperty(clientX509Util.getSslContextSupplierClassProperty(), SslContextSupplier.class.getName());
@@ -532,103 +683,135 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
 
     // This test makes sure that client-initiated TLS renegotiation does not
     // succeed. We explicitly disable it at the top of X509Util.java.
-    @Test(expected = SSLHandshakeException.class)
-    public void testClientRenegotiationFails() throws Throwable {
-        int port = PortAssignment.unique();
-        ExecutorService workerPool = Executors.newCachedThreadPool();
-        final SSLServerSocket listeningSocket = x509Util.createSSLServerSocket();
-        SSLSocket clientSocket = null;
-        SSLSocket serverSocket = null;
-        final AtomicInteger handshakesCompleted = new AtomicInteger(0);
-        final CountDownLatch handshakeCompleted = new CountDownLatch(1);
-        try {
-            InetSocketAddress localServerAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), port);
-            listeningSocket.bind(localServerAddress);
-            Future<SSLSocket> acceptFuture;
-            acceptFuture = workerPool.submit(new Callable<SSLSocket>() {
-                @Override
-                public SSLSocket call() throws Exception {
-                    SSLSocket sslSocket = (SSLSocket) listeningSocket.accept();
-                    sslSocket.addHandshakeCompletedListener(new HandshakeCompletedListener() {
-                        @Override
-                        public void handshakeCompleted(HandshakeCompletedEvent handshakeCompletedEvent) {
-                            handshakesCompleted.getAndIncrement();
-                            handshakeCompleted.countDown();
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testClientRenegotiationFails(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Throwable {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(SSLHandshakeException.class, () -> {
+            int port = PortAssignment.unique();
+            ExecutorService workerPool = Executors.newCachedThreadPool();
+            final SSLServerSocket listeningSocket = x509Util.createSSLServerSocket();
+            SSLSocket clientSocket = null;
+            SSLSocket serverSocket = null;
+            final AtomicInteger handshakesCompleted = new AtomicInteger(0);
+            final CountDownLatch handshakeCompleted = new CountDownLatch(1);
+            try {
+                InetSocketAddress localServerAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), port);
+                listeningSocket.bind(localServerAddress);
+                Future<SSLSocket> acceptFuture;
+                acceptFuture = workerPool.submit(new Callable<SSLSocket>() {
+                    @Override
+                    public SSLSocket call() throws Exception {
+                        SSLSocket sslSocket = (SSLSocket) listeningSocket.accept();
+                        sslSocket.addHandshakeCompletedListener(new HandshakeCompletedListener() {
+                            @Override
+                            public void handshakeCompleted(HandshakeCompletedEvent handshakeCompletedEvent) {
+                                handshakesCompleted.getAndIncrement();
+                                handshakeCompleted.countDown();
+                            }
+                        });
+                        assertEquals(1, sslSocket.getInputStream().read());
+                        try {
+                            // 2nd read is after the renegotiation attempt and will fail
+                            sslSocket.getInputStream().read();
+                            return sslSocket;
+                        } catch (Exception e) {
+                            forceClose(sslSocket);
+                            throw e;
                         }
-                    });
-                    assertEquals(1, sslSocket.getInputStream().read());
-                    try {
-                        // 2nd read is after the renegotiation attempt and will fail
-                        sslSocket.getInputStream().read();
-                        return sslSocket;
-                    } catch (Exception e) {
-                        forceClose(sslSocket);
-                        throw e;
                     }
+                });
+                clientSocket = x509Util.createSSLSocket();
+                clientSocket.connect(localServerAddress);
+                clientSocket.getOutputStream().write(1);
+                // Attempt to renegotiate after establishing the connection
+                clientSocket.startHandshake();
+                clientSocket.getOutputStream().write(1);
+                // The exception is thrown on the server side, we need to unwrap it
+                try {
+                    serverSocket = acceptFuture.get();
+                } catch (ExecutionException e) {
+                    throw e.getCause();
                 }
-            });
-            clientSocket = x509Util.createSSLSocket();
-            clientSocket.connect(localServerAddress);
-            clientSocket.getOutputStream().write(1);
-            // Attempt to renegotiate after establishing the connection
-            clientSocket.startHandshake();
-            clientSocket.getOutputStream().write(1);
-            // The exception is thrown on the server side, we need to unwrap it
-            try {
-                serverSocket = acceptFuture.get();
-            } catch (ExecutionException e) {
-                throw e.getCause();
+            } finally {
+                forceClose(serverSocket);
+                forceClose(clientSocket);
+                forceClose(listeningSocket);
+                workerPool.shutdown();
+                // Make sure the first handshake completed and only the second
+                // one failed.
+                handshakeCompleted.await(5, TimeUnit.SECONDS);
+                assertEquals(1, handshakesCompleted.get());
             }
-        } finally {
-            forceClose(serverSocket);
-            forceClose(clientSocket);
-            forceClose(listeningSocket);
-            workerPool.shutdown();
-            // Make sure the first handshake completed and only the second
-            // one failed.
-            handshakeCompleted.await(5, TimeUnit.SECONDS);
-            assertEquals(1, handshakesCompleted.get());
-        }
+        });
     }
 
-    @Test
-    public void testGetDefaultCipherSuitesJava8() {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testGetDefaultCipherSuitesJava8(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         String[] cipherSuites = X509Util.getDefaultCipherSuitesForJavaVersion("1.8");
         // Java 8 default should have the CBC suites first
         assertTrue(cipherSuites[0].contains("CBC"));
     }
 
-    @Test
-    public void testGetDefaultCipherSuitesJava9() {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testGetDefaultCipherSuitesJava9(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         String[] cipherSuites = X509Util.getDefaultCipherSuitesForJavaVersion("9");
         // Java 9+ default should have the GCM suites first
         assertTrue(cipherSuites[0].contains("GCM"));
     }
 
-    @Test
-    public void testGetDefaultCipherSuitesJava10() {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testGetDefaultCipherSuitesJava10(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         String[] cipherSuites = X509Util.getDefaultCipherSuitesForJavaVersion("10");
         // Java 9+ default should have the GCM suites first
         assertTrue(cipherSuites[0].contains("GCM"));
     }
 
-    @Test
-    public void testGetDefaultCipherSuitesJava11() {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testGetDefaultCipherSuitesJava11(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         String[] cipherSuites = X509Util.getDefaultCipherSuitesForJavaVersion("11");
         // Java 9+ default should have the GCM suites first
         assertTrue(cipherSuites[0].contains("GCM"));
     }
 
-    @Test
-    public void testGetDefaultCipherSuitesUnknownVersion() {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testGetDefaultCipherSuitesUnknownVersion(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
         String[] cipherSuites = X509Util.getDefaultCipherSuitesForJavaVersion("notaversion");
         // If version can't be parsed, use the more conservative Java 8 default
         assertTrue(cipherSuites[0].contains("CBC"));
     }
 
-    @Test(expected = NullPointerException.class)
-    public void testGetDefaultCipherSuitesNullVersion() {
-        X509Util.getDefaultCipherSuitesForJavaVersion(null);
+    @ParameterizedTest
+    @MethodSource("data")
+    public void testGetDefaultCipherSuitesNullVersion(
+            X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex)
+            throws Exception {
+        init(caKeyType, certKeyType, keyPassword, paramIndex);
+        assertThrows(NullPointerException.class, () -> {
+            X509Util.getDefaultCipherSuitesForJavaVersion(null);
+        });
     }
 
     // Warning: this will reset the x509Util

+ 10 - 13
zookeeper-server/src/test/java/org/apache/zookeeper/common/ZKConfigTest.java

@@ -18,30 +18,23 @@
 
 package org.apache.zookeeper.common;
 
-
-import static org.junit.Assert.assertEquals;
-import java.util.concurrent.TimeUnit;
-import org.junit.After;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.Timeout;
-
-
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 public class ZKConfigTest {
 
     X509Util x509Util = new ClientX509Util();
 
-    @Rule
-    public Timeout timeout = new Timeout(10, TimeUnit.SECONDS);
-
-    @After
+    @AfterEach
     public void tearDown() throws Exception {
         System.clearProperty(x509Util.getSslProtocolProperty());
     }
 
     // property is not set we should get the default value
     @Test
+    @Timeout(value = 10)
     public void testBooleanRetrievalFromPropertyDefault() {
         ZKConfig conf = new ZKConfig();
         String prop = "UnSetProperty" + System.currentTimeMillis();
@@ -52,6 +45,7 @@ public class ZKConfigTest {
 
     // property is set to an valid boolean, we should get the set value
     @Test
+    @Timeout(value = 10)
     public void testBooleanRetrievalFromProperty() {
         boolean value = true;
         boolean defaultValue = false;
@@ -63,6 +57,7 @@ public class ZKConfigTest {
 
     // property is set but with white spaces in the beginning
     @Test
+    @Timeout(value = 10)
     public void testBooleanRetrievalFromPropertyWithWhitespacesInBeginning() {
         boolean value = true;
         boolean defaultValue = false;
@@ -74,6 +69,7 @@ public class ZKConfigTest {
 
     // property is set but with white spaces at the end
     @Test
+    @Timeout(value = 10)
     public void testBooleanRetrievalFromPropertyWithWhitespacesAtEnd() {
         boolean value = true;
         boolean defaultValue = false;
@@ -85,6 +81,7 @@ public class ZKConfigTest {
 
     // property is set but with white spaces at the beginning and the end
     @Test
+    @Timeout(value = 10)
     public void testBooleanRetrievalFromPropertyWithWhitespacesAtBeginningAndEnd() {
         boolean value = true;
         boolean defaultValue = false;

+ 5 - 5
zookeeper-server/src/test/java/org/apache/zookeeper/common/ZKHostnameVerifierTest.java

@@ -18,14 +18,14 @@
 
 package org.apache.zookeeper.common;
 
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.ByteArrayInputStream;
 import java.io.InputStream;
 import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
 import javax.net.ssl.SSLException;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 /**
  * Note: These test cases (and resources) have been taken from the Apache HttpComponents project.
@@ -34,7 +34,7 @@ public class ZKHostnameVerifierTest {
 
     private ZKHostnameVerifier impl;
 
-    @Before
+    @BeforeEach
     public void setup() {
         impl = new ZKHostnameVerifier();
     }
@@ -153,7 +153,7 @@ public class ZKHostnameVerifierTest {
                                  final X509Certificate x509) {
         try {
             hv.verify(host, x509);
-            Assert.fail("HostnameVerifier shouldn't allow [" + host + "]");
+            fail("HostnameVerifier shouldn't allow [" + host + "]");
         } catch (final SSLException e) {
             // whew!  we're okay!
         }

+ 7 - 7
zookeeper-server/src/test/java/org/apache/zookeeper/common/ZKTrustManagerTest.java

@@ -49,10 +49,10 @@ import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
 import org.bouncycastle.jce.provider.BouncyCastleProvider;
 import org.bouncycastle.operator.ContentSigner;
 import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
 
@@ -68,7 +68,7 @@ public class ZKTrustManagerTest extends ZKTestCase {
     private InetAddress mockInetAddress;
     private Socket mockSocket;
 
-    @BeforeClass
+    @BeforeAll
     public static void createKeyPair() throws Exception {
         Security.addProvider(new BouncyCastleProvider());
         KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
@@ -76,12 +76,12 @@ public class ZKTrustManagerTest extends ZKTestCase {
         keyPair = keyPairGenerator.genKeyPair();
     }
 
-    @AfterClass
+    @AfterAll
     public static void removeBouncyCastleProvider() throws Exception {
         Security.removeProvider("BC");
     }
 
-    @Before
+    @BeforeEach
     public void setup() throws Exception {
         mockX509ExtendedTrustManager = mock(X509ExtendedTrustManager.class);
 

+ 25 - 26
zookeeper-server/src/test/java/org/apache/zookeeper/server/BlueThrottleTest.java

@@ -18,17 +18,16 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.util.Random;
 import java.util.concurrent.TimeoutException;
 import org.apache.zookeeper.ZKTestCase;
 import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.test.ClientBase;
 import org.apache.zookeeper.test.QuorumUtil;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -67,7 +66,7 @@ public class BlueThrottleTest extends ZKTestCase {
     @Test
     public void testThrottleDisabled() {
         BlueThrottle throttler = new BlueThrottle();
-        assertTrue("Throttle should be disabled by default", throttler.checkLimit(1));
+        assertTrue(throttler.checkLimit(1), "Throttle should be disabled by default");
     }
 
     @Test
@@ -75,8 +74,8 @@ public class BlueThrottleTest extends ZKTestCase {
         BlueThrottle throttler = new BlueThrottle();
         throttler.setMaxTokens(1);
         throttler.setFillTime(2000);
-        assertTrue("First request should be allowed", throttler.checkLimit(1));
-        assertFalse("Second request should be denied", throttler.checkLimit(1));
+        assertTrue(throttler.checkLimit(1), "First request should be allowed");
+        assertFalse(throttler.checkLimit(1), "Second request should be denied");
     }
 
     @Test
@@ -84,12 +83,12 @@ public class BlueThrottleTest extends ZKTestCase {
         BlueThrottle throttler = new BlueThrottle();
         throttler.setMaxTokens(1);
         throttler.setFillTime(500);
-        assertTrue("First request should be allowed", throttler.checkLimit(1));
-        assertFalse("Second request should be denied", throttler.checkLimit(1));
+        assertTrue(throttler.checkLimit(1), "First request should be allowed");
+        assertFalse(throttler.checkLimit(1), "Second request should be denied");
 
         //wait for the bucket to be refilled
         Thread.sleep(750);
-        assertTrue("Third request should be allowed since we've got a new token", throttler.checkLimit(1));
+        assertTrue(throttler.checkLimit(1), "Third request should be allowed since we've got a new token");
     }
 
     @Test
@@ -103,21 +102,21 @@ public class BlueThrottleTest extends ZKTestCase {
         for (int i = 0; i < maxTokens; i++) {
             throttler.checkLimit(1);
         }
-        assertEquals("All tokens should be used up by now", throttler.getMaxTokens(), throttler.getDeficit());
+        assertEquals(throttler.getMaxTokens(), throttler.getDeficit(), "All tokens should be used up by now");
 
         Thread.sleep(110);
         throttler.checkLimit(1);
-        assertFalse("Dropping probability should still be zero", throttler.getDropChance() > 0);
+        assertFalse(throttler.getDropChance() > 0, "Dropping probability should still be zero");
 
         //allow bucket to be refilled
         Thread.sleep(1500);
 
         for (int i = 0; i < maxTokens; i++) {
-            assertTrue("The first " + maxTokens + " requests should be allowed", throttler.checkLimit(1));
+            assertTrue(throttler.checkLimit(1), "The first " + maxTokens + " requests should be allowed");
         }
 
         for (int i = 0; i < maxTokens; i++) {
-            assertFalse("The latter " + maxTokens + " requests should be denied", throttler.checkLimit(1));
+            assertFalse(throttler.checkLimit(1), "The latter " + maxTokens + " requests should be denied");
         }
     }
 
@@ -134,12 +133,12 @@ public class BlueThrottleTest extends ZKTestCase {
         for (int i = 0; i < maxTokens; i++) {
             throttler.checkLimit(1);
         }
-        assertEquals("All tokens should be used up by now", throttler.getMaxTokens(), throttler.getDeficit());
+        assertEquals(throttler.getMaxTokens(), throttler.getDeficit(), "All tokens should be used up by now");
 
         Thread.sleep(120);
         //this will trigger dropping probability being increased
         throttler.checkLimit(1);
-        assertTrue("Dropping probability should be increased", throttler.getDropChance() > 0);
+        assertTrue(throttler.getDropChance() > 0, "Dropping probability should be increased");
         LOG.info("Dropping probability is {}", throttler.getDropChance());
 
         //allow bucket to be refilled
@@ -154,7 +153,7 @@ public class BlueThrottleTest extends ZKTestCase {
         }
 
         LOG.info("Send {} requests, {} are accepted", maxTokens, accepted);
-        assertTrue("The dropping should be distributed", accepted < maxTokens);
+        assertTrue(accepted < maxTokens, "The dropping should be distributed");
 
         accepted = 0;
 
@@ -165,7 +164,7 @@ public class BlueThrottleTest extends ZKTestCase {
         }
 
         LOG.info("Send another {} requests, {} are accepted", maxTokens, accepted);
-        assertTrue("Later requests should have a chance", accepted > 0);
+        assertTrue(accepted > 0, "Later requests should have a chance");
     }
 
     private QuorumUtil quorumUtil = new QuorumUtil(1);
@@ -212,7 +211,7 @@ public class BlueThrottleTest extends ZKTestCase {
 
         int connected = connect(10);
 
-        Assert.assertEquals(10, connected);
+        assertEquals(10, connected);
         shutdownQuorum();
     }
 
@@ -227,7 +226,7 @@ public class BlueThrottleTest extends ZKTestCase {
 
 
         int connected = connect(3);
-        Assert.assertEquals(2, connected);
+        assertEquals(2, connected);
         shutdownQuorum();
 
         quorumUtil.enableLocalSession(false);
@@ -239,7 +238,7 @@ public class BlueThrottleTest extends ZKTestCase {
 
 
         connected = connect(3);
-        Assert.assertEquals(2, connected);
+        assertEquals(2, connected);
         shutdownQuorum();
     }
 
@@ -256,7 +255,7 @@ public class BlueThrottleTest extends ZKTestCase {
 
         //try to create 11 local sessions, 10 created, because we have only 10 tokens
         int connected = connect(11);
-        Assert.assertEquals(10, connected);
+        assertEquals(10, connected);
         shutdownQuorum();
 
         quorumUtil.enableLocalSession(false);
@@ -265,14 +264,14 @@ public class BlueThrottleTest extends ZKTestCase {
         quorumUtil.getPeer(1).peer.getActiveServer().connThrottle().setFillCount(0);
         //tyr to create 11 global sessions, 3 created, because we have 10 tokens and each connection needs 3
         connected = connect(11);
-        Assert.assertEquals(3, connected);
+        assertEquals(3, connected);
         shutdownQuorum();
 
         quorumUtil.startAll();
         quorumUtil.getPeer(1).peer.getActiveServer().connThrottle().setMaxTokens(10);
         quorumUtil.getPeer(1).peer.getActiveServer().connThrottle().setFillCount(0);
         connected = connect(2);
-        Assert.assertEquals(2, connected);
+        assertEquals(2, connected);
 
         quorumUtil.shutdown(1);
         watchers[0].waitForDisconnected(RAPID_TIMEOUT);
@@ -293,7 +292,7 @@ public class BlueThrottleTest extends ZKTestCase {
         }
         //each reconnect takes two tokens, we have 3, so only one reconnects
         LOG.info("reconnected {}", reconnected);
-        Assert.assertEquals(1, reconnected);
+        assertEquals(1, reconnected);
         shutdownQuorum();
     }
 }

+ 12 - 9
zookeeper-server/src/test/java/org/apache/zookeeper/server/ByteBufferInputStreamTest.java

@@ -18,22 +18,23 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import java.nio.ByteBuffer;
 import java.nio.charset.StandardCharsets;
 import java.util.Arrays;
 import org.apache.zookeeper.ZKTestCase;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class ByteBufferInputStreamTest extends ZKTestCase {
 
     private static final byte[] DATA_BYTES_0 = "Apache ZooKeeper".getBytes(StandardCharsets.UTF_8);
 
     private static byte[] DATA_BYTES;
-    @BeforeClass
+    @BeforeAll
     public static void setUpClass() {
         int len = DATA_BYTES_0.length + 2;
         DATA_BYTES = new byte[len];
@@ -45,7 +46,7 @@ public class ByteBufferInputStreamTest extends ZKTestCase {
     private ByteBuffer bb;
     private ByteBufferInputStream in;
     private byte[] bs;
-    @Before
+    @BeforeEach
     public void setUp() throws Exception {
         bb = ByteBuffer.wrap(DATA_BYTES);
         in = new ByteBufferInputStream(bb);
@@ -66,9 +67,11 @@ public class ByteBufferInputStreamTest extends ZKTestCase {
         byte[] expected = new byte[]{(byte) 1, (byte) 2, DATA_BYTES[0], (byte) 4};
         assertArrayEquals(expected, bs);
     }
-    @Test(expected = IndexOutOfBoundsException.class)
+    @Test
     public void testReadArrayOffsetLength_LengthTooLarge() throws Exception {
-        in.read(bs, 2, 3);
+        assertThrows(IndexOutOfBoundsException.class, () -> {
+            in.read(bs, 2, 3);
+        });
     }
     @Test
     public void testReadArrayOffsetLength_HitEndOfStream() throws Exception {

+ 5 - 5
zookeeper-server/src/test/java/org/apache/zookeeper/server/CRCTest.java

@@ -19,8 +19,8 @@
 package org.apache.zookeeper.server;
 
 import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.BufferedInputStream;
 import java.io.File;
 import java.io.FileInputStream;
@@ -43,7 +43,7 @@ import org.apache.zookeeper.server.persistence.FileSnap;
 import org.apache.zookeeper.server.persistence.FileTxnLog;
 import org.apache.zookeeper.server.persistence.TxnLog.TxnIterator;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -111,7 +111,7 @@ public class CRCTest extends ZKTestCase {
         ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
         f.startup(zks);
         LOG.info("starting up the zookeeper server .. waiting");
-        assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT), "waiting for server being up");
         ZooKeeper zk = ClientBase.createZKClient(HOSTPORT);
         try {
             for (int i = 0; i < 2000; i++) {
@@ -122,7 +122,7 @@ public class CRCTest extends ZKTestCase {
         }
         f.shutdown();
         zks.shutdown();
-        assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT), "waiting for server down");
 
         File versionDir = new File(tmpDir, "version-2");
         File[] list = versionDir.listFiles();

+ 2 - 2
zookeeper-server/src/test/java/org/apache/zookeeper/server/ConnectionMetricsTest.java

@@ -19,7 +19,7 @@
 package org.apache.zookeeper.server;
 
 import static org.apache.zookeeper.server.NIOServerCnxnFactory.ZOOKEEPER_NIO_SESSIONLESS_CNXN_TIMEOUT;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
@@ -41,7 +41,7 @@ import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.metrics.MetricsUtils;
 import org.apache.zookeeper.test.ClientBase;
 import org.apache.zookeeper.test.QuorumUtil;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 

+ 52 - 38
zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateContainerTest.java

@@ -18,11 +18,11 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
@@ -43,13 +43,17 @@ import org.apache.zookeeper.ZooDefs;
 import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.data.Stat;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 public class CreateContainerTest extends ClientBase {
 
     private ZooKeeper zk;
     private Semaphore completedContainerDeletions;
 
+    @BeforeEach
     @Override
     public void setUp() throws Exception {
         super.setUp();
@@ -68,19 +72,22 @@ public class CreateContainerTest extends ClientBase {
         serverFactory.zkServer.setZKDatabase(testDatabase);
     }
 
+    @AfterEach
     @Override
     public void tearDown() throws Exception {
         super.tearDown();
         zk.close();
     }
 
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testCreate() throws KeeperException, InterruptedException {
         createNoStatVerifyResult("/foo");
         createNoStatVerifyResult("/foo/child");
     }
 
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testCreateWithStat() throws KeeperException, InterruptedException {
         Stat stat = createWithStatVerifyResult("/foo");
         Stat childStat = createWithStatVerifyResult("/foo/child");
@@ -89,7 +96,8 @@ public class CreateContainerTest extends ClientBase {
     }
 
     @SuppressWarnings("ConstantConditions")
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testCreateWithNullStat() throws KeeperException, InterruptedException {
         final String name = "/foo";
         assertNull(zk.exists(name, false));
@@ -102,7 +110,8 @@ public class CreateContainerTest extends ClientBase {
         assertNotNull(zk.exists(name, false));
     }
 
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testSimpleDeletion() throws KeeperException, InterruptedException {
         zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
         zk.create("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
@@ -112,10 +121,11 @@ public class CreateContainerTest extends ClientBase {
         containerManager.checkContainers();
 
         assertTrue(completedContainerDeletions.tryAcquire(1, TimeUnit.SECONDS));
-        assertNull("Container should have been deleted", zk.exists("/foo", false));
+        assertNull(zk.exists("/foo", false), "Container should have been deleted");
     }
 
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testMultiWithContainerSimple() throws KeeperException, InterruptedException {
         Op createContainer = Op.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
         zk.multi(Collections.singletonList(createContainer));
@@ -124,7 +134,8 @@ public class CreateContainerTest extends ClientBase {
         assertEquals(dataTree.getContainers().size(), 1);
     }
 
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testMultiWithContainer() throws KeeperException, InterruptedException {
         Op createContainer = Op.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
         Op createChild = Op.create("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
@@ -139,7 +150,7 @@ public class CreateContainerTest extends ClientBase {
         containerManager.checkContainers();
 
         assertTrue(completedContainerDeletions.tryAcquire(1, TimeUnit.SECONDS));
-        assertNull("Container should have been deleted", zk.exists("/foo", false));
+        assertNull(zk.exists("/foo", false), "Container should have been deleted");
 
         createContainer = Op.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
         createChild = Op.create("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
@@ -149,10 +160,11 @@ public class CreateContainerTest extends ClientBase {
         containerManager.checkContainers();
 
         assertTrue(completedContainerDeletions.tryAcquire(1, TimeUnit.SECONDS));
-        assertNull("Container should have been deleted", zk.exists("/foo", false));
+        assertNull(zk.exists("/foo", false), "Container should have been deleted");
     }
 
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testSimpleDeletionAsync() throws KeeperException, InterruptedException {
         final CountDownLatch latch = new CountDownLatch(1);
         AsyncCallback.Create2Callback cb = (rc, path, ctx, name, stat) -> {
@@ -168,10 +180,11 @@ public class CreateContainerTest extends ClientBase {
         containerManager.checkContainers();
 
         assertTrue(completedContainerDeletions.tryAcquire(1, TimeUnit.SECONDS));
-        assertNull("Container should have been deleted", zk.exists("/foo", false));
+        assertNull(zk.exists("/foo", false), "Container should have been deleted");
     }
 
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testCascadingDeletion() throws KeeperException, InterruptedException {
         zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
         zk.create("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
@@ -184,28 +197,29 @@ public class CreateContainerTest extends ClientBase {
         containerManager.checkContainers();
         assertTrue(completedContainerDeletions.tryAcquire(1, TimeUnit.SECONDS));
 
-        assertNull("Container should have been deleted", zk.exists("/foo/bar", false));
-        assertNull("Container should have been deleted", zk.exists("/foo", false));
+        assertNull(zk.exists("/foo/bar", false), "Container should have been deleted");
+        assertNull(zk.exists("/foo", false), "Container should have been deleted");
     }
 
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testFalseEmpty() throws KeeperException, InterruptedException {
         zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
         zk.create("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
 
         ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100) {
-            @Override
-            protected Collection<String> getCandidates() {
+            @Override protected Collection<String> getCandidates() {
                 return Collections.singletonList("/foo");
             }
         };
         containerManager.checkContainers();
 
         assertTrue(completedContainerDeletions.tryAcquire(1, TimeUnit.SECONDS));
-        assertNotNull("Container should have not been deleted", zk.exists("/foo", false));
+        assertNotNull(zk.exists("/foo", false), "Container should have not been deleted");
     }
 
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testMaxPerMinute() throws InterruptedException {
         final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
         RequestProcessor processor = new RequestProcessor() {
@@ -246,7 +260,8 @@ public class CreateContainerTest extends ClientBase {
         assertEquals(queue.poll(5, TimeUnit.SECONDS), "/four");
     }
 
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testMaxNeverUsedInterval() throws KeeperException, InterruptedException {
         zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
         AtomicLong elapsed = new AtomicLong(0);
@@ -265,49 +280,48 @@ public class CreateContainerTest extends ClientBase {
         };
         containerManager.checkContainers(); // elapsed time will appear to be 0 - container will not get deleted
         assertEquals(deletesQty.get(), 0);
-        assertNotNull("Container should not have been deleted", zk.exists("/foo", false));
+        assertNotNull(zk.exists("/foo", false), "Container should not have been deleted");
 
         elapsed.set(10000);
         containerManager.checkContainers(); // elapsed time will appear to be 10000 - container should get deleted
         assertTrue(completedContainerDeletions.tryAcquire(1, TimeUnit.SECONDS));
-        assertNull("Container should have been deleted", zk.exists("/foo", false));
+        assertNull(zk.exists("/foo", false), "Container should have been deleted");
     }
 
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testZeroMaxNeverUsedInterval() throws KeeperException, InterruptedException {
         zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
         AtomicInteger deletesQty = new AtomicInteger(0);
         ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100, 0) {
-            @Override
-            protected void postDeleteRequest(Request request) throws RequestProcessor.RequestProcessorException {
+            @Override protected void postDeleteRequest(Request request) throws RequestProcessor.RequestProcessorException {
                 deletesQty.incrementAndGet();
                 super.postDeleteRequest(request);
             }
 
-            @Override
-            protected long getElapsed(DataNode node) {
+            @Override protected long getElapsed(DataNode node) {
                 return 10000;   // some number greater than 0
             }
         };
         containerManager.checkContainers(); // elapsed time will appear to be 0 - container will not get deleted
         assertEquals(deletesQty.get(), 0);
-        assertNotNull("Container should not have been deleted", zk.exists("/foo", false));
+        assertNotNull(zk.exists("/foo", false), "Container should not have been deleted");
     }
 
     private void createNoStatVerifyResult(String newName) throws KeeperException, InterruptedException {
-        assertNull("Node existed before created", zk.exists(newName, false));
+        assertNull(zk.exists(newName, false), "Node existed before created");
         zk.create(newName, newName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
-        assertNotNull("Node was not created as expected", zk.exists(newName, false));
+        assertNotNull(zk.exists(newName, false), "Node was not created as expected");
     }
 
     private Stat createWithStatVerifyResult(String newName) throws KeeperException, InterruptedException {
-        assertNull("Node existed before created", zk.exists(newName, false));
+        assertNull(zk.exists(newName, false), "Node existed before created");
         Stat stat = new Stat();
         zk.create(newName, newName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER, stat);
         validateCreateStat(stat, newName);
 
         Stat referenceStat = zk.exists(newName, false);
-        assertNotNull("Node was not created as expected", referenceStat);
+        assertNotNull(referenceStat, "Node was not created as expected");
         assertEquals(referenceStat, stat);
 
         return stat;

+ 46 - 33
zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateTTLTest.java

@@ -18,10 +18,11 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
@@ -41,7 +42,10 @@ import org.apache.zookeeper.proto.CreateTTLRequest;
 import org.apache.zookeeper.proto.ReplyHeader;
 import org.apache.zookeeper.proto.RequestHeader;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInfo;
 
 public class CreateTTLTest extends ClientBase {
 
@@ -51,13 +55,20 @@ public class CreateTTLTest extends ClientBase {
 
     @Override
     public void setUp() throws Exception {
+        // to be able to get the test method name a testInfo object is needed
+        // to override the parent's setUp method we need this empty method
+    }
+
+    @BeforeEach
+    public void setUp(TestInfo testInfo) throws Exception {
         System.setProperty(
             EphemeralType.EXTENDED_TYPES_ENABLED_PROPERTY,
-            disabledTests.contains(getTestName()) ? "false" : "true");
+            disabledTests.contains(testInfo.getTestMethod().get().getName()) ? "false" : "true");
         super.setUpWithServerId(254);
         zk = createClient();
     }
 
+    @AfterEach
     @Override
     public void tearDown() throws Exception {
         System.clearProperty(EphemeralType.EXTENDED_TYPES_ENABLED_PROPERTY);
@@ -74,11 +85,11 @@ public class CreateTTLTest extends ClientBase {
         final AtomicLong fakeElapsed = new AtomicLong(0);
         ContainerManager containerManager = newContainerManager(fakeElapsed);
         containerManager.checkContainers();
-        assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+        assertNotNull(zk.exists("/foo", false), "Ttl node should not have been deleted yet");
 
         fakeElapsed.set(1000);
         containerManager.checkContainers();
-        assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
+        assertNull(zk.exists("/foo", false), "Ttl node should have been deleted");
     }
 
     @Test
@@ -89,16 +100,16 @@ public class CreateTTLTest extends ClientBase {
         CreateTTLRequest request = new CreateTTLRequest(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL.toFlag(), -100);
         CreateResponse response = new CreateResponse();
         ReplyHeader r = zk.submitRequest(h, request, response, null);
-        assertEquals("An invalid CreateTTLRequest should throw BadArguments", r.getErr(), Code.BADARGUMENTS.intValue());
-        assertNull("An invalid CreateTTLRequest should not result in znode creation", zk.exists(path, false));
+        assertEquals(r.getErr(), Code.BADARGUMENTS.intValue(), "An invalid CreateTTLRequest should throw BadArguments");
+        assertNull(zk.exists(path, false), "An invalid CreateTTLRequest should not result in znode creation");
 
         request = new CreateTTLRequest(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL.toFlag(),
                                        EphemeralType.TTL.maxValue()
                                                + 1);
         response = new CreateResponse();
         r = zk.submitRequest(h, request, response, null);
-        assertEquals("An invalid CreateTTLRequest should throw BadArguments", r.getErr(), Code.BADARGUMENTS.intValue());
-        assertNull("An invalid CreateTTLRequest should not result in znode creation", zk.exists(path, false));
+        assertEquals(r.getErr(), Code.BADARGUMENTS.intValue(), "An invalid CreateTTLRequest should throw BadArguments");
+        assertNull(zk.exists(path, false), "An invalid CreateTTLRequest should not result in znode creation");
     }
 
     @Test
@@ -109,8 +120,8 @@ public class CreateTTLTest extends ClientBase {
         CreateTTLRequest request = new CreateTTLRequest(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL.toFlag(), EphemeralType.TTL.maxValue());
         CreateResponse response = new CreateResponse();
         ReplyHeader r = zk.submitRequest(h, request, response, null);
-        assertEquals("EphemeralType.getMaxTTL() should succeed", r.getErr(), Code.OK.intValue());
-        assertNotNull("Node should exist", zk.exists(path, false));
+        assertEquals(r.getErr(), Code.OK.intValue(), "EphemeralType.getMaxTTL() should succeed");
+        assertNotNull(zk.exists(path, false), "Node should exist");
     }
 
     @Test
@@ -122,11 +133,11 @@ public class CreateTTLTest extends ClientBase {
         final AtomicLong fakeElapsed = new AtomicLong(0);
         ContainerManager containerManager = newContainerManager(fakeElapsed);
         containerManager.checkContainers();
-        assertNotNull("Ttl node should not have been deleted yet", zk.exists(path, false));
+        assertNotNull(zk.exists(path, false), "Ttl node should not have been deleted yet");
 
         fakeElapsed.set(1000);
         containerManager.checkContainers();
-        assertNull("Ttl node should have been deleted", zk.exists(path, false));
+        assertNull(zk.exists(path, false), "Ttl node should have been deleted");
     }
 
     @Test
@@ -139,11 +150,11 @@ public class CreateTTLTest extends ClientBase {
         final AtomicLong fakeElapsed = new AtomicLong(0);
         ContainerManager containerManager = newContainerManager(fakeElapsed);
         containerManager.checkContainers();
-        assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+        assertNotNull(zk.exists("/foo", false), "Ttl node should not have been deleted yet");
 
         fakeElapsed.set(1000);
         containerManager.checkContainers();
-        assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
+        assertNull(zk.exists("/foo", false), "Ttl node should have been deleted");
     }
 
     @Test
@@ -155,18 +166,18 @@ public class CreateTTLTest extends ClientBase {
         final AtomicLong fakeElapsed = new AtomicLong(0);
         ContainerManager containerManager = newContainerManager(fakeElapsed);
         containerManager.checkContainers();
-        assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+        assertNotNull(zk.exists("/foo", false), "Ttl node should not have been deleted yet");
 
         for (int i = 0; i < 10; ++i) {
             fakeElapsed.set(50);
             zk.setData("/foo", new byte[i + 1], -1);
             containerManager.checkContainers();
-            assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+            assertNotNull(zk.exists("/foo", false), "Ttl node should not have been deleted yet");
         }
 
         fakeElapsed.set(200);
         containerManager.checkContainers();
-        assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
+        assertNull(zk.exists("/foo", false), "Ttl node should have been deleted");
     }
 
     @Test
@@ -180,21 +191,21 @@ public class CreateTTLTest extends ClientBase {
         final AtomicLong fakeElapsed = new AtomicLong(0);
         ContainerManager containerManager = newContainerManager(fakeElapsed);
         containerManager.checkContainers();
-        assertNotNull("node should not have been deleted yet", zk.exists("/a", false));
-        assertNotNull("node should not have been deleted yet", zk.exists(sequentialPath, false));
-        assertNotNull("node should never be deleted", zk.exists("/c", false));
+        assertNotNull(zk.exists("/a", false), "node should not have been deleted yet");
+        assertNotNull(zk.exists(sequentialPath, false), "node should not have been deleted yet");
+        assertNotNull(zk.exists("/c", false), "node should never be deleted");
 
         fakeElapsed.set(110);
         containerManager.checkContainers();
-        assertNull("node should have been deleted", zk.exists("/a", false));
-        assertNotNull("node should not have been deleted yet", zk.exists(sequentialPath, false));
-        assertNotNull("node should never be deleted", zk.exists("/c", false));
+        assertNull(zk.exists("/a", false), "node should have been deleted");
+        assertNotNull(zk.exists(sequentialPath, false), "node should not have been deleted yet");
+        assertNotNull(zk.exists("/c", false), "node should never be deleted");
 
         fakeElapsed.set(210);
         containerManager.checkContainers();
-        assertNull("node should have been deleted", zk.exists("/a", false));
-        assertNull("node should have been deleted", zk.exists(sequentialPath, false));
-        assertNotNull("node should never be deleted", zk.exists("/c", false));
+        assertNull(zk.exists("/a", false), "node should have been deleted");
+        assertNull(zk.exists(sequentialPath, false), "node should have been deleted");
+        assertNotNull(zk.exists("/c", false), "node should never be deleted");
     }
 
     @Test
@@ -236,10 +247,12 @@ public class CreateTTLTest extends ClientBase {
         }
     }
 
-    @Test(expected = KeeperException.UnimplementedException.class)
+    @Test
     public void testDisabled() throws KeeperException, InterruptedException {
-        // note, setUp() enables this test based on the test name
-        zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, new Stat(), 100);
+        assertThrows(KeeperException.UnimplementedException.class, () -> {
+            // note, setUp() enables this test based on the test name
+            zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, new Stat(), 100);
+        });
     }
 
     private ContainerManager newContainerManager(final AtomicLong fakeElapsed) {

+ 4 - 4
zookeeper-server/src/test/java/org/apache/zookeeper/server/DataNodeTest.java

@@ -18,11 +18,11 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.util.Set;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class DataNodeTest {
 

+ 47 - 44
zookeeper-server/src/test/java/org/apache/zookeeper/server/DataTreeTest.java

@@ -18,12 +18,12 @@
 
 package org.apache.zookeeper.server;
 
-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.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.DataInputStream;
@@ -51,7 +51,8 @@ import org.apache.zookeeper.data.Stat;
 import org.apache.zookeeper.metrics.MetricsUtils;
 import org.apache.zookeeper.txn.CreateTxn;
 import org.apache.zookeeper.txn.TxnHeader;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -63,7 +64,8 @@ public class DataTreeTest extends ZKTestCase {
      * For ZOOKEEPER-1755 - Test race condition when taking dumpEphemerals and
      * removing the session related ephemerals from DataTree structure
      */
-    @Test(timeout = 60000)
+    @Test
+    @Timeout(value = 60)
     public void testDumpEphemerals() throws Exception {
         int count = 1000;
         long session = 1000;
@@ -91,7 +93,7 @@ public class DataTreeTest extends ZKTestCase {
         killZkClientSession(session, zxid, dataTree, count);
         running.set(false);
         thread.join();
-        assertFalse("Should have got exception while dumpEphemerals!", exceptionDuringDumpEphemerals.get());
+        assertFalse(exceptionDuringDumpEphemerals.get(), "Should have got exception while dumpEphemerals!");
     }
 
     private void killZkClientSession(long session, long zxid, final DataTree dataTree, int count) {
@@ -107,7 +109,8 @@ public class DataTreeTest extends ZKTestCase {
         }
     }
 
-    @Test(timeout = 60000)
+    @Test
+    @Timeout(value = 60)
     public void testRootWatchTriggered() throws Exception {
         DataTree dt = new DataTree();
 
@@ -122,13 +125,14 @@ public class DataTreeTest extends ZKTestCase {
         // add a new node, should trigger a watch
         dt.createNode("/xyz", new byte[0], null, 0, dt.getNode("/").stat.getCversion() + 1, 1, 1);
 
-        assertTrue("Root node watch not triggered", fire.isDone());
+        assertTrue(fire.isDone(), "Root node watch not triggered");
     }
 
     /**
      * For ZOOKEEPER-1046 test if cversion is getting incremented correctly.
      */
-    @Test(timeout = 60000)
+    @Test
+    @Timeout(value = 60)
     public void testIncrementCversion() throws Exception {
         try {
             // digestCalculator gets initialized for the new DataTree constructor based on the system property
@@ -142,15 +146,9 @@ public class DataTreeTest extends ZKTestCase {
             dt.setCversionPzxid("/test/", prevCversion + 1, prevPzxid + 1);
             int newCversion = zk.stat.getCversion();
             long newPzxid = zk.stat.getPzxid();
-            assertTrue("<cversion, pzxid> verification failed. Expected: <"
-                                      + (prevCversion + 1)
-                                      + ", "
-                                      + (prevPzxid + 1)
-                                      + ">, found: <"
-                                      + newCversion
-                                      + ", "
-                                      + newPzxid
-                                      + ">", (newCversion == prevCversion + 1 && newPzxid == prevPzxid + 1));
+            assertTrue((newCversion == prevCversion + 1 && newPzxid == prevPzxid + 1),
+                "<cversion, pzxid> verification failed. Expected: <" + (prevCversion + 1) + ", "
+                    + (prevPzxid + 1) + ">, found: <" + newCversion + ", " + newPzxid + ">");
             assertNotEquals(digestBefore, dt.getTreeDigest());
         } finally {
             ZooKeeperServer.setDigestEnabled(false);
@@ -168,7 +166,8 @@ public class DataTreeTest extends ZKTestCase {
         parent = dt.getNode("/");
         int newCversion = parent.stat.getCversion();
         long newPzxid = parent.stat.getPzxid();
-        assertTrue("<cversion, pzxid> verification failed. Expected: <"
+        assertTrue((newCversion >= currentCversion && newPzxid >= currentPzxid),
+            "<cversion, pzxid> verification failed. Expected: <"
                                   + currentCversion
                                   + ", "
                                   + currentPzxid
@@ -176,7 +175,7 @@ public class DataTreeTest extends ZKTestCase {
                                   + newCversion
                                   + ", "
                                   + newPzxid
-                                  + ">", (newCversion >= currentCversion && newPzxid >= currentPzxid));
+                                  + ">");
     }
 
     @Test
@@ -226,7 +225,8 @@ public class DataTreeTest extends ZKTestCase {
         }
     }
 
-    @Test(timeout = 60000)
+    @Test
+    @Timeout(value = 60)
     public void testPathTrieClearOnDeserialize() throws Exception {
 
         //Create a DataTree with quota nodes so PathTrie get updated
@@ -254,7 +254,7 @@ public class DataTreeTest extends ZKTestCase {
         PathTrie pTrie = (PathTrie) pfield.get(dserTree);
 
         //Check that the node path is removed from pTrie
-        assertEquals("/bug is still in pTrie", "/", pTrie.findMaxPrefix("/bug"));
+        assertEquals("/", pTrie.findMaxPrefix("/bug"), "/bug is still in pTrie");
     }
 
 
@@ -264,10 +264,11 @@ public class DataTreeTest extends ZKTestCase {
      * This can cause the system experiences hanging issues similar to ZooKeeper-2201.
      * This test verifies the fix that we should not hold ACL cache during dumping aclcache to snapshots
     */
-    @Test(timeout = 60000)
+    @Test
+    @Timeout(value = 60)
     public void testSerializeDoesntLockACLCacheWhileWriting() throws Exception {
         DataTree tree = new DataTree();
-        tree.createNode("/marker", new byte[]{42}, null, -1, 1, 1, 1);
+        tree.createNode("/marker", new byte[] { 42 }, null, -1, 1, 1, 1);
         final AtomicBoolean ranTestCase = new AtomicBoolean();
         DataOutputStream out = new DataOutputStream(new ByteArrayOutputStream());
         BinaryOutputArchive oa = new BinaryOutputArchive(out) {
@@ -290,7 +291,7 @@ public class DataTreeTest extends ZKTestCase {
                     boolean acquired = semaphore.tryAcquire(30, TimeUnit.SECONDS);
                     //This is the real assertion - could another thread lock
                     //the ACLCache
-                    assertTrue("Couldn't acquire a lock on the ACLCache while we were calling tree.serialize", acquired);
+                    assertTrue(acquired, "Couldn't acquire a lock on the ACLCache while we were calling tree.serialize");
                 } catch (InterruptedException e1) {
                     throw new RuntimeException(e1);
                 }
@@ -303,15 +304,16 @@ public class DataTreeTest extends ZKTestCase {
         tree.serialize(oa, "test");
 
         //Let's make sure that we hit the code that ran the real assertion above
-        assertTrue("Didn't find the expected node", ranTestCase.get());
+        assertTrue(ranTestCase.get(), "Didn't find the expected node");
     }
 
     /* ZOOKEEPER-3531 - similarly for aclCache.deserialize, we should not hold lock either
     */
-    @Test(timeout = 60000)
+    @Test
+    @Timeout(value = 60)
     public void testDeserializeDoesntLockACLCacheWhileReading() throws Exception {
         DataTree tree = new DataTree();
-        tree.createNode("/marker", new byte[]{42}, null, -1, 1, 1, 1);
+        tree.createNode("/marker", new byte[] { 42 }, null, -1, 1, 1, 1);
         final AtomicBoolean ranTestCase = new AtomicBoolean();
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         DataOutputStream out = new DataOutputStream(baos);
@@ -341,7 +343,7 @@ public class DataTreeTest extends ZKTestCase {
                     boolean acquired = semaphore.tryAcquire(30, TimeUnit.SECONDS);
                     //This is the real assertion - could another thread lock
                     //the ACLCache
-                    assertTrue("Couldn't acquire a lock on the ACLCache while we were calling tree.deserialize", acquired);
+                    assertTrue(acquired, "Couldn't acquire a lock on the ACLCache while we were calling tree.deserialize");
                 } catch (InterruptedException e1) {
                     throw new RuntimeException(e1);
                 }
@@ -354,7 +356,7 @@ public class DataTreeTest extends ZKTestCase {
         tree2.deserialize(ia, "test");
 
         //Let's make sure that we hit the code that ran the real assertion above
-        assertTrue("Didn't find the expected node", ranTestCase.get());
+        assertTrue(ranTestCase.get(), "Didn't find the expected node");
     }
 
     /*
@@ -365,10 +367,11 @@ public class DataTreeTest extends ZKTestCase {
      * currently being written, i.e. that DataTree.serializeNode does not hold
      * the DataNode lock while calling OutputArchive.writeRecord.
      */
-    @Test(timeout = 60000)
+    @Test
+    @Timeout(value = 60)
     public void testSerializeDoesntLockDataNodeWhileWriting() throws Exception {
         DataTree tree = new DataTree();
-        tree.createNode("/marker", new byte[]{42}, null, -1, 1, 1, 1);
+        tree.createNode("/marker", new byte[] { 42 }, null, -1, 1, 1, 1);
         final DataNode markerNode = tree.getNode("/marker");
         final AtomicBoolean ranTestCase = new AtomicBoolean();
         DataOutputStream out = new DataOutputStream(new ByteArrayOutputStream());
@@ -395,7 +398,7 @@ public class DataTreeTest extends ZKTestCase {
                             boolean acquired = semaphore.tryAcquire(30, TimeUnit.SECONDS);
                             //This is the real assertion - could another thread lock
                             //the DataNode we're currently writing
-                            assertTrue("Couldn't acquire a lock on the DataNode while we were calling tree.serialize", acquired);
+                            assertTrue(acquired, "Couldn't acquire a lock on the DataNode while we were calling tree.serialize");
                         } catch (InterruptedException e1) {
                             throw new RuntimeException(e1);
                         }
@@ -410,19 +413,19 @@ public class DataTreeTest extends ZKTestCase {
         tree.serialize(oa, "test");
 
         //Let's make sure that we hit the code that ran the real assertion above
-        assertTrue("Didn't find the expected node", ranTestCase.get());
+        assertTrue(ranTestCase.get(), "Didn't find the expected node");
     }
 
-    @Test(timeout = 60000)
+    @Test
+    @Timeout(value = 60)
     public void testReconfigACLClearOnDeserialize() throws Exception {
-
         DataTree tree = new DataTree();
         // simulate the upgrading scenario, where the reconfig znode
         // doesn't exist and the acl cache is empty
         tree.deleteNode(ZooDefs.CONFIG_NODE, 1);
         tree.getReferenceCountedAclCache().aclIndex = 0;
 
-        assertEquals("expected to have 1 acl in acl cache map", 0, tree.aclCacheSize());
+        assertEquals(0, tree.aclCacheSize(), "expected to have 1 acl in acl cache map");
 
         // serialize the data with one znode with acl
         tree.createNode("/bug", new byte[20], ZooDefs.Ids.OPEN_ACL_UNSAFE, -1, 1, 1, 1);
@@ -436,15 +439,15 @@ public class DataTreeTest extends ZKTestCase {
         BinaryInputArchive ia = BinaryInputArchive.getArchive(bais);
         tree.deserialize(ia, "test");
 
-        assertEquals("expected to have 1 acl in acl cache map", 1, tree.aclCacheSize());
-        assertEquals("expected to have the same acl", ZooDefs.Ids.OPEN_ACL_UNSAFE, tree.getACL("/bug", new Stat()));
+        assertEquals(1, tree.aclCacheSize(), "expected to have 1 acl in acl cache map");
+        assertEquals(ZooDefs.Ids.OPEN_ACL_UNSAFE, tree.getACL("/bug", new Stat()), "expected to have the same acl");
 
         // simulate the upgrading case where the config node will be created
         // again after leader election
         tree.addConfigNode();
 
-        assertEquals("expected to have 2 acl in acl cache map", 2, tree.aclCacheSize());
-        assertEquals("expected to have the same acl", ZooDefs.Ids.OPEN_ACL_UNSAFE, tree.getACL("/bug", new Stat()));
+        assertEquals(2, tree.aclCacheSize(), "expected to have 2 acl in acl cache map");
+        assertEquals(ZooDefs.Ids.OPEN_ACL_UNSAFE, tree.getACL("/bug", new Stat()), "expected to have the same acl");
     }
 
     @Test

+ 15 - 15
zookeeper-server/src/test/java/org/apache/zookeeper/server/DatadirCleanupManagerTest.java

@@ -21,13 +21,13 @@ package org.apache.zookeeper.server;
 import static org.apache.zookeeper.server.DatadirCleanupManager.PurgeTaskStatus.COMPLETED;
 import static org.apache.zookeeper.server.DatadirCleanupManager.PurgeTaskStatus.NOT_STARTED;
 import static org.apache.zookeeper.server.DatadirCleanupManager.PurgeTaskStatus.STARTED;
-import static org.junit.Assert.assertEquals;
+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.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class DatadirCleanupManagerTest extends ZKTestCase {
 
@@ -35,7 +35,7 @@ public class DatadirCleanupManagerTest extends ZKTestCase {
     private File snapDir;
     private File dataLogDir;
 
-    @Before
+    @BeforeEach
     public void setUp() throws Exception {
         File dataDir = ClientBase.createTmpDir();
         snapDir = dataDir;
@@ -46,33 +46,33 @@ public class DatadirCleanupManagerTest extends ZKTestCase {
     public void testPurgeTask() throws Exception {
         purgeMgr = new DatadirCleanupManager(snapDir, dataLogDir, 3, 1);
         purgeMgr.start();
-        assertEquals("Data log directory is not set as configured", dataLogDir, purgeMgr.getDataLogDir());
-        assertEquals("Snapshot directory is not set as configured", snapDir, purgeMgr.getSnapDir());
-        assertEquals("Snapshot retain count is not set as configured", 3, purgeMgr.getSnapRetainCount());
-        assertEquals("Purge task is not started", STARTED, purgeMgr.getPurgeTaskStatus());
+        assertEquals(dataLogDir, purgeMgr.getDataLogDir(), "Data log directory is not set as configured");
+        assertEquals(snapDir, purgeMgr.getSnapDir(), "Snapshot directory is not set as configured");
+        assertEquals(3, purgeMgr.getSnapRetainCount(), "Snapshot retain count is not set as configured");
+        assertEquals(STARTED, purgeMgr.getPurgeTaskStatus(), "Purge task is not started");
         purgeMgr.shutdown();
-        assertEquals("Purge task is still running after shutdown", COMPLETED, purgeMgr.getPurgeTaskStatus());
+        assertEquals(COMPLETED, purgeMgr.getPurgeTaskStatus(), "Purge task is still running after shutdown");
     }
 
     @Test
     public void testWithZeroPurgeInterval() throws Exception {
         purgeMgr = new DatadirCleanupManager(snapDir, dataLogDir, 3, 0);
         purgeMgr.start();
-        assertEquals("Purge task is scheduled with zero purge interval", NOT_STARTED, purgeMgr.getPurgeTaskStatus());
+        assertEquals(NOT_STARTED, purgeMgr.getPurgeTaskStatus(), "Purge task is scheduled with zero purge interval");
         purgeMgr.shutdown();
-        assertEquals("Purge task is scheduled with zero purge interval", NOT_STARTED, purgeMgr.getPurgeTaskStatus());
+        assertEquals(NOT_STARTED, purgeMgr.getPurgeTaskStatus(), "Purge task is scheduled with zero purge interval");
     }
 
     @Test
     public void testWithNegativePurgeInterval() throws Exception {
         purgeMgr = new DatadirCleanupManager(snapDir, dataLogDir, 3, -1);
         purgeMgr.start();
-        assertEquals("Purge task is scheduled with negative purge interval", NOT_STARTED, purgeMgr.getPurgeTaskStatus());
+        assertEquals(NOT_STARTED, purgeMgr.getPurgeTaskStatus(), "Purge task is scheduled with negative purge interval");
         purgeMgr.shutdown();
-        assertEquals("Purge task is scheduled with negative purge interval", NOT_STARTED, purgeMgr.getPurgeTaskStatus());
+        assertEquals(NOT_STARTED, purgeMgr.getPurgeTaskStatus(), "Purge task is scheduled with negative purge interval");
     }
 
-    @After
+    @AfterEach
     public void tearDown() throws Exception {
         if (purgeMgr != null) {
             purgeMgr.shutdown();

+ 2 - 2
zookeeper-server/src/test/java/org/apache/zookeeper/server/DeserializationPerfTest.java

@@ -18,7 +18,7 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
@@ -26,7 +26,7 @@ import org.apache.jute.BinaryInputArchive;
 import org.apache.jute.BinaryOutputArchive;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.ZKTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 

+ 13 - 9
zookeeper-server/src/test/java/org/apache/zookeeper/server/Emulate353TTLTest.java

@@ -19,10 +19,10 @@
 package org.apache.zookeeper.server;
 
 import static org.hamcrest.CoreMatchers.equalTo;
-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.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
 import java.util.concurrent.atomic.AtomicLong;
 import org.apache.zookeeper.CreateMode;
 import org.apache.zookeeper.KeeperException;
@@ -30,12 +30,15 @@ import org.apache.zookeeper.TestableZooKeeper;
 import org.apache.zookeeper.ZooDefs;
 import org.apache.zookeeper.data.Stat;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class Emulate353TTLTest extends ClientBase {
 
     private TestableZooKeeper zk;
 
+    @BeforeEach
     @Override
     public void setUp() throws Exception {
         System.setProperty(EphemeralType.EXTENDED_TYPES_ENABLED_PROPERTY, "true");
@@ -44,6 +47,7 @@ public class Emulate353TTLTest extends ClientBase {
         zk = createClient();
     }
 
+    @AfterEach
     @Override
     public void tearDown() throws Exception {
         System.clearProperty(EphemeralType.EXTENDED_TYPES_ENABLED_PROPERTY);
@@ -61,11 +65,11 @@ public class Emulate353TTLTest extends ClientBase {
         final AtomicLong fakeElapsed = new AtomicLong(0);
         ContainerManager containerManager = newContainerManager(fakeElapsed);
         containerManager.checkContainers();
-        assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+        assertNotNull(zk.exists("/foo", false), "Ttl node should not have been deleted yet");
 
         fakeElapsed.set(1000);
         containerManager.checkContainers();
-        assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
+        assertNull(zk.exists("/foo", false), "Ttl node should have been deleted");
     }
 
     @Test
@@ -78,11 +82,11 @@ public class Emulate353TTLTest extends ClientBase {
         final AtomicLong fakeElapsed = new AtomicLong(0);
         ContainerManager containerManager = newContainerManager(fakeElapsed);
         containerManager.checkContainers();
-        assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+        assertNotNull(zk.exists("/foo", false), "Ttl node should not have been deleted yet");
 
         fakeElapsed.set(1000);
         containerManager.checkContainers();
-        assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
+        assertNull(zk.exists("/foo", false), "Ttl node should have been deleted");
     }
 
     @Test

+ 15 - 12
zookeeper-server/src/test/java/org/apache/zookeeper/server/EphemeralTypeTest.java

@@ -19,22 +19,23 @@
 package org.apache.zookeeper.server;
 
 import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.fail;
 import org.apache.zookeeper.CreateMode;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class EphemeralTypeTest {
 
-    @Before
+    @BeforeEach
     public void setUp() {
         System.setProperty(EphemeralType.EXTENDED_TYPES_ENABLED_PROPERTY, "true");
     }
 
-    @After
+    @AfterEach
     public void tearDown() {
         System.clearProperty(EphemeralType.EXTENDED_TYPES_ENABLED_PROPERTY);
     }
@@ -92,11 +93,13 @@ public class EphemeralTypeTest {
         assertThat(EphemeralType.get(0xff00000000000000L), equalTo(EphemeralType.TTL));
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void testEphemeralOwner_extendedFeature_extendedTypeUnsupported() {
-        // 0xff = Extended feature is ON
-        // 0x0001 = Unsupported extended type id (1)
-        EphemeralType.get(0xff00010000000000L);
+        assertThrows(IllegalArgumentException.class, () -> {
+            // 0xff = Extended feature is ON
+            // 0x0001 = Unsupported extended type id (1)
+            EphemeralType.get(0xff00010000000000L);
+        });
     }
 
 }

+ 7 - 7
zookeeper-server/src/test/java/org/apache/zookeeper/server/FinalRequestProcessorTest.java

@@ -18,9 +18,9 @@
 
 package org.apache.zookeeper.server;
 
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.equalTo;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.eq;
@@ -43,8 +43,8 @@ import org.apache.zookeeper.data.Stat;
 import org.apache.zookeeper.proto.GetACLRequest;
 import org.apache.zookeeper.proto.GetACLResponse;
 import org.apache.zookeeper.proto.ReplyHeader;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
 
@@ -58,7 +58,7 @@ public class FinalRequestProcessorTest {
     private ByteBuffer bb;
     private FinalRequestProcessor processor;
 
-    @Before
+    @BeforeEach
     public void setUp() throws KeeperException.NoNodeException, IOException {
         testACLs.clear();
         testACLs.addAll(Arrays.asList(new ACL(ZooDefs.Perms.ALL, new Id("digest", "user:secrethash")), new ACL(ZooDefs.Perms.ADMIN, new Id("digest", "adminuser:adminsecret")), new ACL(ZooDefs.Perms.READ, new Id("world", "anyone"))));
@@ -171,7 +171,7 @@ public class FinalRequestProcessorTest {
         processor.processRequest(r);
 
         // Assert
-        assertTrue("Not a GetACL response. Auth failed?", responseRecord[0] instanceof GetACLResponse);
+        assertTrue(responseRecord[0] instanceof GetACLResponse, "Not a GetACL response. Auth failed?");
         GetACLResponse rsp = (GetACLResponse) responseRecord[0];
         assertThat("Number of ACLs in the response are different", rsp.getAcl().size(), equalTo(2));
 
@@ -181,7 +181,7 @@ public class FinalRequestProcessorTest {
     }
 
     private void assertMasked(boolean masked) {
-        assertTrue("Not a GetACL response. Auth failed?", responseRecord[0] instanceof GetACLResponse);
+        assertTrue(responseRecord[0] instanceof GetACLResponse, "Not a GetACL response. Auth failed?");
         GetACLResponse rsp = (GetACLResponse) responseRecord[0];
         assertThat("Number of ACLs in the response are different", rsp.getAcl().size(), equalTo(3));
 

+ 7 - 8
zookeeper-server/src/test/java/org/apache/zookeeper/server/FollowerRequestProcessorTest.java

@@ -19,8 +19,8 @@
 package org.apache.zookeeper.server.quorum;
 
 import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import org.apache.zookeeper.CreateMode;
 import org.apache.zookeeper.PortAssignment;
 import org.apache.zookeeper.ZooDefs.Ids;
@@ -30,8 +30,8 @@ import org.apache.zookeeper.server.ServerMetrics;
 import org.apache.zookeeper.server.util.PortForwarder;
 import org.apache.zookeeper.test.ClientBase;
 import org.apache.zookeeper.test.ObserverMasterTestBase;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
 
 public class FollowerRequestProcessorTest extends ObserverMasterTestBase {
 
@@ -65,9 +65,8 @@ public class FollowerRequestProcessorTest extends ObserverMasterTestBase {
         forwarder = setUp(OM_PROXY_PORT, true);
 
         q3.start();
-        assertTrue(
-            "waiting for server 3 being up",
-            ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS, CONNECTION_TIMEOUT),
+                "waiting for server 3 being up");
 
         // Connect with observer zookeeper
         zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_OBS, ClientBase.CONNECTION_TIMEOUT, this);
@@ -77,7 +76,7 @@ public class FollowerRequestProcessorTest extends ObserverMasterTestBase {
         ServerMetrics.getMetrics().resetAll();
     }
 
-    @After
+    @AfterEach
     public void cleanup() throws Exception {
         System.setProperty(FollowerRequestProcessor.SKIP_LEARNER_REQUEST_TO_NEXT_PROCESSOR, "false");
 

+ 5 - 6
zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapCountTest.java

@@ -19,8 +19,8 @@
 package org.apache.zookeeper.server;
 
 import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.File;
 import java.io.FileWriter;
 import java.io.IOException;
@@ -29,7 +29,7 @@ import org.apache.zookeeper.Watcher;
 import org.apache.zookeeper.ZKTestCase;
 import org.apache.zookeeper.common.PathUtils;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -109,9 +109,8 @@ public class InvalidSnapCountTest extends ZKTestCase implements Watcher {
         MainThread main = new MainThread(CLIENT_PORT);
         main.start();
 
-        assertTrue(
-                "waiting for server being up",
-                ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT),
+                "waiting for server being up");
 
         assertEquals(SyncRequestProcessor.getSnapCount(), 2);
 

+ 3 - 3
zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapshotTest.java

@@ -18,14 +18,14 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.File;
 import java.io.RandomAccessFile;
 import org.apache.zookeeper.CreateMode;
 import org.apache.zookeeper.ZooDefs.Ids;
 import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -72,7 +72,7 @@ public class InvalidSnapshotTest extends ClientBase {
         // verify that the expected data exists and wasn't lost
         zk = createClient();
         try {
-            assertTrue("the node should exist", (zk.exists("/invalidsnap-1999", false) != null));
+            assertTrue((zk.exists("/invalidsnap-1999", false) != null), "the node should exist");
         } finally {
             zk.close();
         }

+ 16 - 14
zookeeper-server/src/test/java/org/apache/zookeeper/server/MultiOpSessionUpgradeTest.java

@@ -18,12 +18,12 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.nio.ByteBuffer;
@@ -44,7 +44,8 @@ import org.apache.zookeeper.server.quorum.QuorumPeer;
 import org.apache.zookeeper.server.quorum.QuorumZooKeeperServer;
 import org.apache.zookeeper.server.quorum.UpgradeableSessionTracker;
 import org.apache.zookeeper.test.QuorumBase;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -52,6 +53,7 @@ public class MultiOpSessionUpgradeTest extends QuorumBase {
 
     protected static final Logger LOG = LoggerFactory.getLogger(MultiOpSessionUpgradeTest.class);
 
+    @BeforeEach
     @Override
     public void setUp() throws Exception {
         localSessionsEnabled = true;
@@ -68,9 +70,9 @@ public class MultiOpSessionUpgradeTest extends QuorumBase {
         zk.create(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
 
         QuorumZooKeeperServer server = getConnectedServer(zk.getSessionId());
-        assertNotNull("unable to find server interlocutor", server);
+        assertNotNull(server, "unable to find server interlocutor");
         UpgradeableSessionTracker sessionTracker = (UpgradeableSessionTracker) server.getSessionTracker();
-        assertFalse("session already global", sessionTracker.isGlobalSession(zk.getSessionId()));
+        assertFalse(sessionTracker.isGlobalSession(zk.getSessionId()), "session already global");
 
         List<OpResult> multi = null;
         try {
@@ -89,7 +91,7 @@ public class MultiOpSessionUpgradeTest extends QuorumBase {
         assertEquals(data, new String(zk.getData(path + "/e", false, null)));
         assertEquals(data, new String(zk.getData(path + "/p", false, null)));
         assertEquals(data, new String(zk.getData(path + "/q", false, null)));
-        assertTrue("session not promoted", sessionTracker.isGlobalSession(zk.getSessionId()));
+        assertTrue(sessionTracker.isGlobalSession(zk.getSessionId()), "session not promoted");
     }
 
     @Test
@@ -100,13 +102,13 @@ public class MultiOpSessionUpgradeTest extends QuorumBase {
         zk.create(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
 
         QuorumZooKeeperServer server = getConnectedServer(zk.getSessionId());
-        assertNotNull("unable to find server interlocutor", server);
+        assertNotNull(server, "unable to find server interlocutor");
 
         Request readRequest = makeGetDataRequest(path, zk.getSessionId());
         Request createRequest = makeCreateRequest(path + "/e", zk.getSessionId());
-        assertNull("tried to upgrade on a read", server.checkUpgradeSession(readRequest));
-        assertNotNull("failed to upgrade on a create", server.checkUpgradeSession(createRequest));
-        assertNull("tried to upgrade after successful promotion", server.checkUpgradeSession(createRequest));
+        assertNull(server.checkUpgradeSession(readRequest), "tried to upgrade on a read");
+        assertNotNull(server.checkUpgradeSession(createRequest), "failed to upgrade on a create");
+        assertNull(server.checkUpgradeSession(createRequest), "tried to upgrade after successful promotion");
     }
 
     private Request makeGetDataRequest(String path, long sessionId) throws IOException {

+ 15 - 10
zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnFactoryTest.java

@@ -18,43 +18,48 @@
 
 package org.apache.zookeeper.server;
 
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import java.io.IOException;
 import java.net.InetSocketAddress;
 import java.net.ServerSocket;
 import java.net.SocketException;
 import org.apache.zookeeper.PortAssignment;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class NIOServerCnxnFactoryTest {
 
     private InetSocketAddress listenAddress;
     private NIOServerCnxnFactory factory;
 
-    @Before
+    @BeforeEach
     public void setUp() throws IOException {
         listenAddress = new InetSocketAddress(PortAssignment.unique());
         factory = new NIOServerCnxnFactory();
         factory.configure(listenAddress, 100);
     }
 
-    @After
+    @AfterEach
     public void tearDown() {
         if (factory != null) {
             factory.shutdown();
         }
     }
 
-    @Test(expected = SocketException.class)
+    @Test
     public void testStartupWithoutStart_SocketAlreadyBound() throws IOException {
-        ServerSocket ss = new ServerSocket(listenAddress.getPort());
+        assertThrows(SocketException.class, () -> {
+            ServerSocket ss = new ServerSocket(listenAddress.getPort());
+        });
     }
 
-    @Test(expected = SocketException.class)
+    @Test
     public void testStartupWithStart_SocketAlreadyBound() throws IOException {
-        factory.start();
-        ServerSocket ss = new ServerSocket(listenAddress.getPort());
+        assertThrows(SocketException.class, () -> {
+            factory.start();
+            ServerSocket ss = new ServerSocket(listenAddress.getPort());
+        });
     }
 
     @Test

+ 11 - 9
zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnTest.java

@@ -18,12 +18,12 @@
 
 package org.apache.zookeeper.server;
 
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.greaterThan;
-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.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.IOException;
 import org.apache.zookeeper.CreateMode;
 import org.apache.zookeeper.KeeperException;
@@ -31,7 +31,8 @@ import org.apache.zookeeper.ZooDefs.Ids;
 import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.server.quorum.BufferStats;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -42,7 +43,8 @@ public class NIOServerCnxnTest extends ClientBase {
     /**
      * Test operations on ServerCnxn after socket closure.
      */
-    @Test(timeout = 60000)
+    @Test
+    @Timeout(value = 60)
     public void testOperationsAfterCnxnClose() throws IOException, InterruptedException, KeeperException {
         final ZooKeeper zk = createClient();
 
@@ -50,10 +52,11 @@ public class NIOServerCnxnTest extends ClientBase {
         try {
             // make sure zkclient works
             zk.create(path, "test".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
-            assertNotNull("Didn't create znode:" + path, zk.exists(path, false));
+            assertNotNull(zk.exists(path, false), "Didn't create znode:" + path);
             // Defaults ServerCnxnFactory would be instantiated with
             // NIOServerCnxnFactory
-            assertTrue("Didn't instantiate ServerCnxnFactory with NIOServerCnxnFactory!", serverFactory instanceof NIOServerCnxnFactory);
+            assertTrue(serverFactory instanceof NIOServerCnxnFactory,
+                "Didn't instantiate ServerCnxnFactory with NIOServerCnxnFactory!");
             Iterable<ServerCnxn> connections = serverFactory.getConnections();
             for (ServerCnxn serverCnxn : connections) {
                 serverCnxn.close(ServerCnxn.DisconnectReason.CHANNEL_CLOSED_EXCEPTION);
@@ -67,7 +70,6 @@ public class NIOServerCnxnTest extends ClientBase {
         } finally {
             zk.close();
         }
-
     }
 
     @Test

+ 13 - 11
zookeeper-server/src/test/java/org/apache/zookeeper/server/NettyServerCnxnFactoryTest.java

@@ -18,6 +18,10 @@
 
 package org.apache.zookeeper.server;
 
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.net.InetSocketAddress;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.LinkedBlockingQueue;
@@ -32,12 +36,10 @@ import org.apache.zookeeper.server.metric.SimpleCounter;
 import org.apache.zookeeper.test.ClientBase;
 import org.apache.zookeeper.test.SSLAuthTest;
 import org.hamcrest.Matchers;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-
 public class NettyServerCnxnFactoryTest extends ClientBase {
 
     private static final Logger LOG = LoggerFactory
@@ -78,14 +80,14 @@ public class NettyServerCnxnFactoryTest extends ClientBase {
         NettyServerCnxnFactory factory = new NettyServerCnxnFactory();
         factory.configure(addr, 100, -1, false);
         factory.start();
-        Assert.assertTrue(factory.getParentChannel().isActive());
+        assertTrue(factory.getParentChannel().isActive());
 
         factory.reconfigure(addr);
 
         // wait the state change
         Thread.sleep(100);
 
-        Assert.assertTrue(factory.getParentChannel().isActive());
+        assertTrue(factory.getParentChannel().isActive());
     }
 
     @Test
@@ -95,14 +97,14 @@ public class NettyServerCnxnFactoryTest extends ClientBase {
         NettyServerCnxnFactory factory = new NettyServerCnxnFactory();
         factory.configure(addr, 100, -1, false);
         factory.start();
-        Assert.assertTrue(factory.getParentChannel().isActive());
+        assertTrue(factory.getParentChannel().isActive());
 
         factory.reconfigure(new InetSocketAddress("[0:0:0:0:0:0:0:0]", randomPort));
 
         // wait the state change
         Thread.sleep(100);
 
-        Assert.assertTrue(factory.getParentChannel().isActive());
+        assertTrue(factory.getParentChannel().isActive());
     }
 
     /*
@@ -124,7 +126,7 @@ public class NettyServerCnxnFactoryTest extends ClientBase {
         // initializing the statistics
         SimpleCounter tlsHandshakeExceeded = (SimpleCounter) ServerMetrics.getMetrics().TLS_HANDSHAKE_EXCEEDED;
         tlsHandshakeExceeded.reset();
-        Assert.assertEquals(tlsHandshakeExceeded.get(), 0);
+        assertEquals(tlsHandshakeExceeded.get(), 0);
 
         // setting the HandshakeLimit to 3, so only 3 SSL handshakes can happen in parallel
         NettyServerCnxnFactory factory = (NettyServerCnxnFactory) serverFactory;
@@ -150,20 +152,20 @@ public class NettyServerCnxnFactoryTest extends ClientBase {
         int actualConnections = cnxnCreated.get();
         LOG.info("created {} connections", actualConnections);
         if (!allConnectionsCreatedInTime) {
-          Assert.fail(String.format("Only %d out of %d connections created!", actualConnections, cnxnLimit));
+            fail(String.format("Only %d out of %d connections created!", actualConnections, cnxnLimit));
         }
 
         // Assert the server refused some of the connections because the handshake limit was reached
         // (throttling should be greater than 0)
         long handshakeThrottledNum = tlsHandshakeExceeded.get();
         LOG.info("TLS_HANDSHAKE_EXCEEDED: {}", handshakeThrottledNum);
-        Assert.assertThat("The number of handshake throttled should be "
+        assertThat("The number of handshake throttled should be "
                 + "greater than 0", handshakeThrottledNum, Matchers.greaterThan(0L));
 
         // Assert there is no outstanding handshake anymore, all the clients connected in the end
         int outstandingHandshakeNum = factory.getOutstandingHandshakeNum();
         LOG.info("outstanding handshake is {}", outstandingHandshakeNum);
-        Assert.assertThat("The outstanding handshake number should be 0 "
+        assertThat("The outstanding handshake number should be 0 "
                 + "after all cnxns established", outstandingHandshakeNum, Matchers.is(0));
     }
 

+ 29 - 20
zookeeper-server/src/test/java/org/apache/zookeeper/server/NettyServerCnxnTest.java

@@ -18,14 +18,15 @@
 
 package org.apache.zookeeper.server;
 
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.greaterThan;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-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.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.IOException;
 import java.net.ProtocolException;
 import java.nio.charset.StandardCharsets;
@@ -45,7 +46,10 @@ import org.apache.zookeeper.server.quorum.BufferStats;
 import org.apache.zookeeper.test.ClientBase;
 import org.apache.zookeeper.test.SSLAuthTest;
 import org.apache.zookeeper.test.TestByteBufAllocator;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -57,6 +61,7 @@ public class NettyServerCnxnTest extends ClientBase {
 
     private static final Logger LOG = LoggerFactory.getLogger(NettyServerCnxnTest.class);
 
+    @BeforeEach
     @Override
     public void setUp() throws Exception {
         System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, "org.apache.zookeeper.server.NettyServerCnxnFactory");
@@ -66,6 +71,7 @@ public class NettyServerCnxnTest extends ClientBase {
         super.setUp();
     }
 
+    @AfterEach
     @Override
     public void tearDown() throws Exception {
         super.tearDown();
@@ -81,9 +87,10 @@ public class NettyServerCnxnTest extends ClientBase {
      *
      * @see <a href="https://issues.jboss.org/browse/NETTY-412">NETTY-412</a>
      */
-    @Test(timeout = 40000)
+    @Test
+    @Timeout(value = 40)
     public void testSendCloseSession() throws Exception {
-        assertTrue("Didn't instantiate ServerCnxnFactory with NettyServerCnxnFactory!", serverFactory instanceof NettyServerCnxnFactory);
+        assertTrue(serverFactory instanceof NettyServerCnxnFactory, "Didn't instantiate ServerCnxnFactory with NettyServerCnxnFactory!");
 
         final ZooKeeper zk = createClient();
         final ZooKeeperServer zkServer = serverFactory.getZooKeeperServer();
@@ -92,10 +99,10 @@ public class NettyServerCnxnTest extends ClientBase {
             // make sure zkclient works
             zk.create(path, "test".getBytes(StandardCharsets.UTF_8), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
             // set on watch
-            assertNotNull("Didn't create znode:" + path, zk.exists(path, true));
+            assertNotNull(zk.exists(path, true), "Didn't create znode:" + path);
             assertEquals(1, zkServer.getZKDatabase().getDataTree().getWatchCount());
             Iterable<ServerCnxn> connections = serverFactory.getConnections();
-            assertEquals("Mismatch in number of live connections!", 1, serverFactory.getNumAliveConnections());
+            assertEquals(1, serverFactory.getNumAliveConnections(), "Mismatch in number of live connections!");
             for (ServerCnxn serverCnxn : connections) {
                 serverCnxn.sendCloseSession();
             }
@@ -120,12 +127,14 @@ public class NettyServerCnxnTest extends ClientBase {
      * is set to 1. This tests that if more than one connection is attempted, the
      * connection fails.
      */
-    @Test(timeout = 40000, expected = ProtocolException.class)
-    public void testMaxConnectionPerIpSurpased() throws Exception {
-        assertTrue("Did not instantiate ServerCnxnFactory with NettyServerCnxnFactory!", serverFactory instanceof NettyServerCnxnFactory);
-
-        try (final ZooKeeper zk1 = createClient(); final ZooKeeper zk2 = createClient()) {
-        }
+    @Test
+    @Timeout(value = 40)
+    public void testMaxConnectionPerIpSurpased() {
+        assertTrue(serverFactory instanceof NettyServerCnxnFactory, "Did not instantiate ServerCnxnFactory with NettyServerCnxnFactory!");
+        assertThrows(ProtocolException.class, () -> {
+            try (final ZooKeeper zk1 = createClient(); final ZooKeeper zk2 = createClient()) {
+            }
+        });
     }
 
     @Test
@@ -139,7 +148,7 @@ public class NettyServerCnxnTest extends ClientBase {
             assertThat("Last client response size should be greater than 0 after client request was performed", clientResponseStats.getLastBufferSize(), greaterThan(0));
 
             byte[] contents = zk.getData("/a", null, null);
-            assertArrayEquals("unexpected data", "test".getBytes(StandardCharsets.UTF_8), contents);
+            assertArrayEquals("test".getBytes(StandardCharsets.UTF_8), contents, "unexpected data");
         }
     }
 
@@ -175,7 +184,7 @@ public class NettyServerCnxnTest extends ClientBase {
             }
 
             byte[] contents = zk.getData("/a", null, null);
-            assertArrayEquals("unexpected data", "test".getBytes(StandardCharsets.UTF_8), contents);
+            assertArrayEquals("test".getBytes(StandardCharsets.UTF_8), contents, "unexpected data");
 
             // As above, but don't do the throttled read. Make the request bytes wait in the socket
             // input buffer until after throttling is turned off. Need to make sure both modes work.
@@ -193,7 +202,7 @@ public class NettyServerCnxnTest extends ClientBase {
             }
 
             contents = zk.getData("/a", null, null);
-            assertArrayEquals("unexpected data", "test".getBytes(StandardCharsets.UTF_8), contents);
+            assertArrayEquals("test".getBytes(StandardCharsets.UTF_8), contents, "unexpected data");
         }
     }
 

+ 7 - 7
zookeeper-server/src/test/java/org/apache/zookeeper/server/NodeHashMapImplTest.java

@@ -18,24 +18,24 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
 import java.util.Map;
 import java.util.Set;
 import org.apache.zookeeper.ZKTestCase;
 import org.apache.zookeeper.data.StatPersisted;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class NodeHashMapImplTest extends ZKTestCase {
 
-    @Before
+    @BeforeEach
     public void setUp() {
         ZooKeeperServer.setDigestEnabled(true);
     }
 
-    @After
+    @AfterEach
     public void tearDown() {
         ZooKeeperServer.setDigestEnabled(false);
     }

+ 7 - 7
zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorMetricsTest.java

@@ -18,10 +18,10 @@
 
 package org.apache.zookeeper.server;
 
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.number.OrderingComparison.greaterThan;
 import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyLong;
 import static org.mockito.ArgumentMatchers.anyString;
@@ -51,9 +51,9 @@ import org.apache.zookeeper.proto.DeleteRequest;
 import org.apache.zookeeper.proto.SetDataRequest;
 import org.apache.zookeeper.test.ClientBase;
 import org.apache.zookeeper.test.QuorumUtil;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -64,7 +64,7 @@ public class PrepRequestProcessorMetricsTest extends ZKTestCase {
     ZooKeeperServer zks;
     RequestProcessor nextProcessor;
 
-    @Before
+    @BeforeEach
     public void setup() {
         System.setProperty(ZooKeeperServer.SKIP_ACL, "true");
         zks = spy(new ZooKeeperServer());
@@ -88,7 +88,7 @@ public class PrepRequestProcessorMetricsTest extends ZKTestCase {
         ServerMetrics.getMetrics().resetAll();
     }
 
-    @After
+    @AfterEach
     public void tearDown() throws Exception {
         System.clearProperty(ZooKeeperServer.SKIP_ACL);
     }

+ 19 - 19
zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorTest.java

@@ -18,10 +18,10 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 import java.io.ByteArrayOutputStream;
@@ -62,9 +62,9 @@ import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
 import org.apache.zookeeper.server.quorum.flexible.QuorumVerifier;
 import org.apache.zookeeper.test.ClientBase;
 import org.apache.zookeeper.txn.ErrorTxn;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -84,7 +84,7 @@ public class PrepRequestProcessorTest extends ClientBase {
     private boolean isReconfigEnabledPreviously;
     private boolean isStandaloneEnabledPreviously;
 
-    @Before
+    @BeforeEach
     public void setup() throws Exception {
         File tmpDir = ClientBase.createTmpDir();
         ClientBase.setupTestEnv();
@@ -94,14 +94,14 @@ public class PrepRequestProcessorTest extends ClientBase {
 
         servcnxnf = ServerCnxnFactory.createFactory(PORT, -1);
         servcnxnf.startup(zks);
-        assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT), "waiting for server being up ");
         zks.sessionTracker = new MySessionTracker();
 
         isReconfigEnabledPreviously = QuorumPeerConfig.isReconfigEnabled();
         isStandaloneEnabledPreviously = QuorumPeerConfig.isStandaloneEnabled();
     }
 
-    @After
+    @AfterEach
     public void teardown() throws Exception {
         if (servcnxnf != null) {
             servcnxnf.shutdown();
@@ -122,8 +122,8 @@ public class PrepRequestProcessorTest extends ClientBase {
         Request foo = new Request(null, 1L, 1, OpCode.create, ByteBuffer.allocate(3), null);
         processor.pRequest(foo);
 
-        assertEquals("Request should have marshalling error", new ErrorTxn(KeeperException.Code.MARSHALLINGERROR.intValue()), outcome.getTxn());
-        assertTrue("request hasn't been processed in chain", pLatch.await(5, TimeUnit.SECONDS));
+        assertEquals(new ErrorTxn(KeeperException.Code.MARSHALLINGERROR.intValue()), outcome.getTxn(), "Request should have marshalling error");
+        assertTrue(pLatch.await(5, TimeUnit.SECONDS), "request hasn't been processed in chain");
     }
 
     private Request createRequest(Record record, int opCode) throws IOException {
@@ -157,7 +157,7 @@ public class PrepRequestProcessorTest extends ClientBase {
         Request req = createRequest(record, OpCode.multi, false);
 
         processor.pRequest(req);
-        assertTrue("request hasn't been processed in chain", pLatch.await(5, TimeUnit.SECONDS));
+        assertTrue(pLatch.await(5, TimeUnit.SECONDS), "request hasn't been processed in chain");
     }
 
     /**
@@ -173,18 +173,18 @@ public class PrepRequestProcessorTest extends ClientBase {
         process(Arrays.asList(Op.setData("/foo", new byte[0], -1)));
 
         ChangeRecord cr = zks.outstandingChangesForPath.get("/foo");
-        assertNotNull("Change record wasn't set", cr);
-        assertEquals("Record zxid wasn't set correctly", 1, cr.zxid);
+        assertNotNull(cr, "Change record wasn't set");
+        assertEquals(1, cr.zxid, "Record zxid wasn't set correctly");
 
         process(Arrays.asList(Op.delete("/foo", -1)));
         cr = zks.outstandingChangesForPath.get("/foo");
-        assertEquals("Record zxid wasn't set correctly", 2, cr.zxid);
+        assertEquals(2, cr.zxid, "Record zxid wasn't set correctly");
 
         // It should fail and shouldn't change outstanding record.
         process(Arrays.asList(Op.delete("/foo", -1)));
         cr = zks.outstandingChangesForPath.get("/foo");
         // zxid should still be previous result because record's not changed.
-        assertEquals("Record zxid wasn't set correctly", 2, cr.zxid);
+        assertEquals(2, cr.zxid, "Record zxid wasn't set correctly");
     }
 
     @Test
@@ -207,13 +207,13 @@ public class PrepRequestProcessorTest extends ClientBase {
         Record record = new CreateRequest("/foo", "data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT.toFlag());
         pLatch = new CountDownLatch(1);
         processor.pRequest(createRequest(record, OpCode.create, false));
-        assertTrue("request hasn't been processed in chain", pLatch.await(5, TimeUnit.SECONDS));
+        assertTrue(pLatch.await(5, TimeUnit.SECONDS), "request hasn't been processed in chain");
 
         String newMember = "server.0=localhost:" + PortAssignment.unique()  + ":" + PortAssignment.unique() + ":participant";
         record = new ReconfigRequest(null, null, newMember, 0);
         pLatch = new CountDownLatch(1);
         processor.pRequest(createRequest(record, OpCode.reconfig, true));
-        assertTrue("request hasn't been processed in chain", pLatch.await(5, TimeUnit.SECONDS));
+        assertTrue(pLatch.await(5, TimeUnit.SECONDS), "request hasn't been processed in chain");
         assertEquals(outcome.getHdr().getType(), OpCode.reconfig);   // Verifies that there was no error.
     }
 

+ 33 - 33
zookeeper-server/src/test/java/org/apache/zookeeper/server/PurgeTxnTest.java

@@ -18,11 +18,11 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.File;
 import java.io.IOException;
 import java.io.OutputStream;
@@ -49,9 +49,9 @@ import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
 import org.apache.zookeeper.server.persistence.SnapStream;
 import org.apache.zookeeper.server.persistence.Util;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -63,12 +63,12 @@ public class PurgeTxnTest extends ZKTestCase {
     private static final long OP_TIMEOUT_IN_MILLIS = 120000;
     private File tmpDir;
 
-    @Before
+    @BeforeEach
     public void setUp() throws Exception {
         tmpDir = ClientBase.createTmpDir();
     }
 
-    @After
+    @AfterEach
     public void teardown() {
         if (null != tmpDir) {
             ClientBase.recursiveDelete(tmpDir);
@@ -87,7 +87,7 @@ public class PurgeTxnTest extends ZKTestCase {
         final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
         ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
         f.startup(zks);
-        assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT), "waiting for server being up ");
         ZooKeeper zk = ClientBase.createZKClient(HOSTPORT);
         try {
             for (int i = 0; i < 2000; i++) {
@@ -98,7 +98,7 @@ public class PurgeTxnTest extends ZKTestCase {
         }
         f.shutdown();
         zks.getTxnLogFactory().close();
-        assertTrue("waiting for server to shutdown", ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT), "waiting for server to shutdown");
         // now corrupt the snapshot
         PurgeTxnLog.purge(tmpDir, tmpDir, 3);
         FileTxnSnapLog snaplog = new FileTxnSnapLog(tmpDir, tmpDir);
@@ -109,7 +109,7 @@ public class PurgeTxnTest extends ZKTestCase {
                 numSnaps++;
             }
         }
-        assertTrue("exactly 3 snapshots ", (numSnaps == 3));
+        assertTrue((numSnaps == 3), "exactly 3 snapshots ");
         snaplog.close();
         zks.shutdown();
     }
@@ -130,7 +130,7 @@ public class PurgeTxnTest extends ZKTestCase {
         final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
         ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
         f.startup(zks);
-        assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT), "waiting for server being up ");
         final ZooKeeper zk = ClientBase.createZKClient(HOSTPORT);
         final CountDownLatch doPurge = new CountDownLatch(1);
         final CountDownLatch purgeFinished = new CountDownLatch(1);
@@ -153,8 +153,8 @@ public class PurgeTxnTest extends ZKTestCase {
         }.start();
         final int thCount = 3;
         List<String> znodes = manyClientOps(zk, doPurge, thCount, "/invalidsnap");
-        assertTrue("Purging is not finished!", purgeFinished.await(OP_TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS));
-        assertFalse("Purging failed!", opFailed.get());
+        assertTrue(purgeFinished.await(OP_TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS), "Purging is not finished!");
+        assertFalse(opFailed.get(), "Purging failed!");
         for (String znode : znodes) {
             try {
                 zk.getData(znode, false, null);
@@ -179,7 +179,7 @@ public class PurgeTxnTest extends ZKTestCase {
         int offset = 0;
 
         File version2 = new File(tmpDir.toString(), "version-2");
-        assertTrue("Failed to create version_2 dir:" + version2.toString(), version2.mkdir());
+        assertTrue(version2.mkdir(), "Failed to create version_2 dir:" + version2.toString());
 
         // Test that with no snaps, findNValidSnapshots returns empty list
         FileTxnSnapLog txnLog = new FileTxnSnapLog(tmpDir, tmpDir);
@@ -191,10 +191,10 @@ public class PurgeTxnTest extends ZKTestCase {
         for (int i = 0; i < nRecentCount; i++) {
             // simulate log file
             File logFile = new File(version2 + "/log." + Long.toHexString(--counter));
-            assertTrue("Failed to create log File:" + logFile.toString(), logFile.createNewFile());
+            assertTrue(logFile.createNewFile(), "Failed to create log File:" + logFile.toString());
             // simulate snapshot file
             File snapFile = new File(version2 + "/snapshot." + Long.toHexString(--counter));
-            assertTrue("Failed to create snap File:" + snapFile.toString(), snapFile.createNewFile());
+            assertTrue(snapFile.createNewFile(), "Failed to create snap File:" + snapFile.toString());
             makeValidSnapshot(snapFile);
             // add the n recent snap files for assertion
             if (i < nRecentSnap) {
@@ -205,17 +205,17 @@ public class PurgeTxnTest extends ZKTestCase {
         // Test that when we ask for recent snaps we get the number we asked for and
         // the files we expected
         List<File> nRecentValidSnapFiles = txnLog.findNValidSnapshots(nRecentSnap);
-        assertEquals("exactly 4 snapshots ", 4, nRecentValidSnapFiles.size());
+        assertEquals(4, nRecentValidSnapFiles.size(), "exactly 4 snapshots ");
         expectedNRecentSnapFiles.removeAll(nRecentValidSnapFiles);
-        assertEquals("Didn't get the recent snap files", 0, expectedNRecentSnapFiles.size());
+        assertEquals(0, expectedNRecentSnapFiles.size(), "Didn't get the recent snap files");
 
         // Test that when asking for more snaps than we created, we still only get snaps
         // not logs or anything else (per ZOOKEEPER-2420)
         nRecentValidSnapFiles = txnLog.findNValidSnapshots(nRecentCount + 5);
         assertEquals(nRecentCount, nRecentValidSnapFiles.size());
         for (File f : nRecentValidSnapFiles) {
-            assertTrue("findNValidSnapshots() returned a non-snapshot: "
-                                      + f.getPath(), (Util.getZxidFromName(f.getName(), "snapshot") != -1));
+            assertTrue((Util.getZxidFromName(f.getName(), "snapshot") != -1),
+                    "findNValidSnapshots() returned a non-snapshot: " + f.getPath());
         }
 
         txnLog.close();
@@ -233,7 +233,7 @@ public class PurgeTxnTest extends ZKTestCase {
         int fileToPurgeCount = 2;
         AtomicInteger offset = new AtomicInteger(0);
         File version2 = new File(tmpDir.toString(), "version-2");
-        assertTrue("Failed to create version_2 dir:" + version2.toString(), version2.mkdir());
+        assertTrue(version2.mkdir(), "Failed to create version_2 dir:" + version2.toString());
         List<File> snapsToPurge = new ArrayList<File>();
         List<File> logsToPurge = new ArrayList<File>();
         List<File> snaps = new ArrayList<File>();
@@ -284,7 +284,7 @@ public class PurgeTxnTest extends ZKTestCase {
         int nRecentCount = 3;
         AtomicInteger offset = new AtomicInteger(0);
         File version2 = new File(tmpDir.toString(), "version-2");
-        assertTrue("Failed to create version_2 dir:" + version2.toString(), version2.mkdir());
+        assertTrue(version2.mkdir(), "Failed to create version_2 dir:" + version2.toString());
         List<File> snaps = new ArrayList<File>();
         List<File> logs = new ArrayList<File>();
         createDataDirFiles(offset, nRecentCount, testWithPrecedingLogFile, version2, snaps, logs);
@@ -306,7 +306,7 @@ public class PurgeTxnTest extends ZKTestCase {
         int fileToPurgeCount = 2;
         AtomicInteger offset = new AtomicInteger(0);
         File version2 = new File(tmpDir.toString(), "version-2");
-        assertTrue("Failed to create version_2 dir:" + version2.toString(), version2.mkdir());
+        assertTrue(version2.mkdir(), "Failed to create version_2 dir:" + version2.toString());
         List<File> snapsToPurge = new ArrayList<File>();
         List<File> logsToPurge = new ArrayList<File>();
         List<File> snaps = new ArrayList<File>();
@@ -433,7 +433,7 @@ public class PurgeTxnTest extends ZKTestCase {
         final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
         ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
         f.startup(zks);
-        assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT), "waiting for server being up ");
         ZooKeeper zk = ClientBase.createZKClient(HOSTPORT);
 
         // Unique identifier for each znode that we create.
@@ -461,7 +461,7 @@ public class PurgeTxnTest extends ZKTestCase {
         f.shutdown();
         zks.getTxnLogFactory().close();
         zks.shutdown();
-        assertTrue("waiting for server to shutdown", ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT), "waiting for server to shutdown");
 
         // Purge snapshot and log files.
         PurgeTxnLog.purge(tmpDir, tmpDir, SNAP_RETAIN_COUNT);
@@ -480,7 +480,7 @@ public class PurgeTxnTest extends ZKTestCase {
          */
         final String lastZnode = "/snap-" + (unique - 1);
         final Stat stat = zk.exists(lastZnode, false);
-        assertNotNull("Last znode does not exist: " + lastZnode, stat);
+        assertNotNull(stat, "Last znode does not exist: " + lastZnode);
 
         // Shutdown for the last time.
         f.shutdown();
@@ -529,7 +529,7 @@ public class PurgeTxnTest extends ZKTestCase {
 
     private File createDataDirLogFile(File version_2, int Zxid) throws IOException {
         File logFile = new File(version_2 + "/log." + Long.toHexString(Zxid));
-        assertTrue("Failed to create log File:" + logFile.toString(), logFile.createNewFile());
+        assertTrue(logFile.createNewFile(), "Failed to create log File:" + logFile.toString());
         return logFile;
     }
 
@@ -544,7 +544,7 @@ public class PurgeTxnTest extends ZKTestCase {
             logs.add(createDataDirLogFile(version_2, --counter));
             // simulate snapshot file
             File snapFile = new File(version_2 + "/snapshot." + Long.toHexString(--counter));
-            assertTrue("Failed to create snap File:" + snapFile.toString(), snapFile.createNewFile());
+            assertTrue(snapFile.createNewFile(), "Failed to create snap File:" + snapFile.toString());
             snaps.add(snapFile);
         }
         if (createPrecedingLogFile) {
@@ -554,7 +554,7 @@ public class PurgeTxnTest extends ZKTestCase {
 
     private void verifyFilesAfterPurge(List<File> logs, boolean exists) {
         for (File file : logs) {
-            assertEquals("After purging, file " + file, exists, file.exists());
+            assertEquals(exists, file.exists(), "After purging, file " + file);
         }
     }
 
@@ -593,7 +593,7 @@ public class PurgeTxnTest extends ZKTestCase {
                 LOG.error("unexpected exception during running ZkClient ops:", exception.get());
                 fail("unexpected exception during running ZkClient ops, see in the logs above");
             }
-            assertTrue("ZkClient ops not finished in time!", operationsFinishedSuccessfully);
+            assertTrue(operationsFinishedSuccessfully, "ZkClient ops not finished in time!");
         } catch (InterruptedException ie) {
             LOG.error("Unexpected exception", ie);
             fail("Unexpected exception occurred!");

+ 4 - 4
zookeeper-server/src/test/java/org/apache/zookeeper/server/ReferenceCountedACLCacheTest.java

@@ -18,9 +18,9 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
@@ -32,7 +32,7 @@ import org.apache.jute.OutputArchive;
 import org.apache.zookeeper.ZooDefs;
 import org.apache.zookeeper.data.ACL;
 import org.apache.zookeeper.data.Id;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class ReferenceCountedACLCacheTest {
 

+ 12 - 13
zookeeper-server/src/test/java/org/apache/zookeeper/server/RequestThrottlerTest.java

@@ -19,8 +19,8 @@
 package org.apache.zookeeper.server;
 
 import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.File;
 import java.io.IOException;
 import java.util.Map;
@@ -35,10 +35,9 @@ import org.apache.zookeeper.ZooDefs;
 import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.metrics.MetricsUtils;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -74,7 +73,7 @@ public class RequestThrottlerTest extends ZKTestCase {
     int connectionLossCount = 0;
 
 
-    @Before
+    @BeforeEach
     public void setup() throws Exception {
         // start a server and create a client
         File tmpDir = ClientBase.createTmpDir();
@@ -84,7 +83,7 @@ public class RequestThrottlerTest extends ZKTestCase {
         f = ServerCnxnFactory.createFactory(PORT, -1);
         f.startup(zks);
         LOG.info("starting up the zookeeper server .. waiting");
-        assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT), "waiting for server being up");
 
         resumeProcess = null;
         submitted = null;
@@ -92,7 +91,7 @@ public class RequestThrottlerTest extends ZKTestCase {
         zk = ClientBase.createZKClient(HOSTPORT);
     }
 
-    @After
+    @AfterEach
     public void tearDown() throws Exception {
         // shut down the server and the client
         if (null != zk) {
@@ -295,9 +294,9 @@ public class RequestThrottlerTest extends ZKTestCase {
 
         // but only two requests can get into the pipeline because they are large requests
         // the connection will be closed
-        Assert.assertEquals(2L, (long) metrics.get("prep_processor_request_queued"));
-        Assert.assertEquals(1L, (long) metrics.get("large_requests_rejected"));
-        Assert.assertEquals(5, connectionLossCount);
+        assertEquals(2L, (long) metrics.get("prep_processor_request_queued"));
+        assertEquals(1L, (long) metrics.get("large_requests_rejected"));
+        assertEquals(5, connectionLossCount);
 
         finished = new CountDownLatch(2);
         // let the requests go through the pipeline
@@ -306,7 +305,7 @@ public class RequestThrottlerTest extends ZKTestCase {
 
         // when the two requests finish, they are stale because the connection is closed already
         metrics = MetricsUtils.currentServerMetrics();
-        Assert.assertEquals(2, (long) metrics.get("stale_replies"));
+        assertEquals(2, (long) metrics.get("stale_replies"));
     }
 
     @Test

+ 1 - 1
zookeeper-server/src/test/java/org/apache/zookeeper/server/SerializationPerfTest.java

@@ -23,7 +23,7 @@ import java.io.OutputStream;
 import org.apache.jute.BinaryOutputArchive;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.ZKTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 

+ 28 - 42
zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerIdTest.java

@@ -18,80 +18,66 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.stream.Stream;
 import org.apache.zookeeper.CreateMode;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.TestableZooKeeper;
-import org.apache.zookeeper.ZKParameterized;
 import org.apache.zookeeper.ZooDefs;
 import org.apache.zookeeper.data.Stat;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
 
-@RunWith(Parameterized.class)
-@Parameterized.UseParametersRunnerFactory(ZKParameterized.RunnerFactory.class)
 public class ServerIdTest extends ClientBase {
 
-    private final TestType testType;
-
-    private static class TestType {
-
-        final boolean ttlsEnabled;
-        final int serverId;
-
-        TestType(boolean ttlsEnabled, int serverId) {
-            this.ttlsEnabled = ttlsEnabled;
-            this.serverId = serverId;
-        }
-
-    }
-
-    @Parameterized.Parameters
-    public static List<TestType> data() {
-        List<TestType> testTypes = new ArrayList<>();
+    public static Stream<Arguments> data() throws Exception {
+        List<Arguments> testTypes = new ArrayList<>();
         for (boolean ttlsEnabled : new boolean[]{true, false}) {
             for (int serverId = 0; serverId <= 255; ++serverId) {
-                testTypes.add(new TestType(ttlsEnabled, serverId));
+                testTypes.add(Arguments.of(ttlsEnabled, serverId));
             }
         }
-        return testTypes;
+        return testTypes.stream();
     }
 
-    @After
+    @AfterEach
     @Override
     public void tearDown() throws Exception {
         super.tearDown();
         System.clearProperty("zookeeper.extendedTypesEnabled");
     }
 
-    public ServerIdTest(TestType testType) {
-        this.testType = testType;
-    }
-
-    @Before
+    @BeforeEach
     @Override
     public void setUp() throws Exception {
-        System.setProperty("zookeeper.extendedTypesEnabled", Boolean.toString(testType.ttlsEnabled));
-        LOG.info("ttlsEnabled: {} - ServerId: {}", testType.ttlsEnabled, testType.serverId);
+        //since parameterized test methods need a parameterized setUp method
+        //the inherited method has to be overridden with an empty function body
+    }
+
+    public void setUp(boolean ttlsEnabled, int serverId) throws Exception {
+        System.setProperty("zookeeper.extendedTypesEnabled", Boolean.toString(ttlsEnabled));
+        LOG.info("ttlsEnabled: {} - ServerId: {}", ttlsEnabled, serverId);
         try {
-            super.setUpWithServerId(testType.serverId);
+            super.setUpWithServerId(serverId);
         } catch (RuntimeException e) {
-            if (testType.ttlsEnabled && (testType.serverId >= EphemeralType.MAX_EXTENDED_SERVER_ID)) {
+            if (ttlsEnabled && (serverId >= EphemeralType.MAX_EXTENDED_SERVER_ID)) {
                 return; // expected
             }
             throw e;
         }
     }
 
-    @Test
-    public void doTest() throws Exception {
-        if (testType.ttlsEnabled && (testType.serverId >= EphemeralType.MAX_EXTENDED_SERVER_ID)) {
+    @ParameterizedTest
+    @MethodSource("data")
+    public void doTest(boolean ttlsEnabled, int serverId) throws Exception {
+        setUp(ttlsEnabled, serverId);
+        if (ttlsEnabled && (serverId >= EphemeralType.MAX_EXTENDED_SERVER_ID)) {
             return;
         }
 
@@ -102,7 +88,7 @@ public class ServerIdTest extends ClientBase {
             zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
             zk.delete("/foo", -1);
 
-            if (testType.ttlsEnabled) {
+            if (ttlsEnabled) {
                 zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, new Stat(), 1000);  // should work
             } else {
                 try {

+ 2 - 2
zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerMetricsTest.java

@@ -18,14 +18,14 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import java.util.Arrays;
 import java.util.Map;
 import java.util.concurrent.ThreadLocalRandom;
 import org.apache.zookeeper.ZKTestCase;
 import org.apache.zookeeper.server.metric.AvgMinMaxCounter;
 import org.apache.zookeeper.server.metric.SimpleCounter;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class ServerMetricsTest extends ZKTestCase {
 

+ 4 - 4
zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerStatsTest.java

@@ -21,17 +21,17 @@ package org.apache.zookeeper.server;
 
 import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.lessThanOrEqualTo;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.mockito.Mockito.mock;
 import org.apache.zookeeper.ZKTestCase;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class ServerStatsTest extends ZKTestCase {
 
     private ServerStats.Provider providerMock;
 
-    @Before
+    @BeforeEach
     public void setUp() {
         providerMock = mock(ServerStats.Provider.class);
     }

+ 18 - 15
zookeeper-server/src/test/java/org/apache/zookeeper/server/SessionTrackerTest.java

@@ -18,12 +18,12 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.File;
 import java.io.IOException;
 import java.util.concurrent.CountDownLatch;
@@ -33,7 +33,8 @@ import org.apache.zookeeper.ZKTestCase;
 import org.apache.zookeeper.ZooDefs.OpCode;
 import org.apache.zookeeper.server.SessionTrackerImpl.SessionImpl;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 /**
  * Testing zk client session logic in sessiontracker
@@ -49,7 +50,8 @@ public class SessionTrackerTest extends ZKTestCase {
      * Verify the create session call in the Leader.FinalRequestProcessor after
      * the session expiration.
      */
-    @Test(timeout = 20000)
+    @Test
+    @Timeout(value = 20)
     public void testAddSessionAfterSessionExpiry() throws Exception {
         RequestThrottler.setMaxRequests(0);
         ZooKeeperServer zks = setupSessionTracker();
@@ -58,7 +60,7 @@ public class SessionTrackerTest extends ZKTestCase {
         zks.sessionTracker.trackSession(sessionId, sessionTimeout);
         SessionTrackerImpl sessionTrackerImpl = (SessionTrackerImpl) zks.sessionTracker;
         SessionImpl sessionImpl = sessionTrackerImpl.sessionsById.get(sessionId);
-        assertNotNull("Sessionid:" + sessionId + " doesn't exists in sessiontracker", sessionImpl);
+        assertNotNull(sessionImpl, "Sessionid:" + sessionId + " doesn't exists in sessiontracker");
 
         // verify the session existence
         Object sessionOwner = new Object();
@@ -77,16 +79,17 @@ public class SessionTrackerTest extends ZKTestCase {
         } catch (KeeperException.SessionExpiredException e) {
             // expected behaviour
         }
-        assertTrue("Session didn't expired", sessionImpl.isClosing());
-        assertFalse("Session didn't expired", sessionTrackerImpl.touchSession(sessionId, sessionTimeout));
-        assertEquals("Duplicate session expiry request has been generated", 1, firstProcessor.getCountOfCloseSessionReq());
+        assertTrue(sessionImpl.isClosing(), "Session didn't expired");
+        assertFalse(sessionTrackerImpl.touchSession(sessionId, sessionTimeout), "Session didn't expired");
+        assertEquals(1, firstProcessor.getCountOfCloseSessionReq(), "Duplicate session expiry request has been generated");
     }
 
     /**
      * Verify the session closure request has reached PrepRequestProcessor soon
      * after session expiration by the session tracker
      */
-    @Test(timeout = 20000)
+    @Test
+    @Timeout(value = 20)
     public void testCloseSessionRequestAfterSessionExpiry() throws Exception {
         ZooKeeperServer zks = setupSessionTracker();
 
@@ -94,7 +97,7 @@ public class SessionTrackerTest extends ZKTestCase {
         zks.sessionTracker.trackSession(sessionId, sessionTimeout);
         SessionTrackerImpl sessionTrackerImpl = (SessionTrackerImpl) zks.sessionTracker;
         SessionImpl sessionImpl = sessionTrackerImpl.sessionsById.get(sessionId);
-        assertNotNull("Sessionid:" + sessionId + " doesn't exists in sessiontracker", sessionImpl);
+        assertNotNull(sessionImpl, "Sessionid:" + sessionId + " doesn't exists in sessiontracker");
 
         // verify the session existence
         Object sessionOwner = new Object();
@@ -107,7 +110,7 @@ public class SessionTrackerTest extends ZKTestCase {
         // while OpCode.closeSession
         sessionTrackerImpl.removeSession(sessionId);
         SessionImpl actualSession = sessionTrackerImpl.sessionsById.get(sessionId);
-        assertNull("Session:" + sessionId + " still exists after removal", actualSession);
+        assertNull(actualSession, "Session:" + sessionId + " still exists after removal");
     }
 
     private ZooKeeperServer setupSessionTracker() throws IOException {

+ 7 - 7
zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotDigestTest.java

@@ -18,8 +18,8 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.ConcurrentHashMap;
@@ -32,9 +32,9 @@ import org.apache.zookeeper.server.metric.SimpleCounter;
 import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
 import org.apache.zookeeper.server.quorum.QuorumPeerMainTest;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.mockito.Mockito;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -46,14 +46,14 @@ public class SnapshotDigestTest extends ClientBase {
     private ZooKeeper zk;
     private ZooKeeperServer server;
 
-    @Before
+    @BeforeEach
     public void setUp() throws Exception {
         super.setUp();
         server = serverFactory.getZooKeeperServer();
         zk = createClient();
     }
 
-    @After
+    @AfterEach
     public void tearDown() throws Exception {
         // server will be closed in super.tearDown
         super.tearDown();

+ 2 - 2
zookeeper-server/src/test/java/org/apache/zookeeper/server/ToStringTest.java

@@ -18,10 +18,10 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
 import org.apache.zookeeper.ZKTestCase;
 import org.apache.zookeeper.proto.SetDataRequest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 /**
  * A misc place to verify toString methods - mainly to make sure they don't

+ 16 - 15
zookeeper-server/src/test/java/org/apache/zookeeper/server/TxnLogDigestTest.java

@@ -18,8 +18,10 @@
 
 package org.apache.zookeeper.server;
 
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.greaterThan;
-import static org.junit.Assert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
 import java.io.File;
 import java.io.IOException;
 import java.util.ArrayList;
@@ -42,11 +44,10 @@ import org.apache.zookeeper.server.quorum.QuorumPeerMainTest;
 import org.apache.zookeeper.test.ClientBase;
 import org.apache.zookeeper.txn.TxnDigest;
 import org.apache.zookeeper.txn.TxnHeader;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -58,14 +59,14 @@ public class TxnLogDigestTest extends ClientBase {
     private ZooKeeper zk;
     private ZooKeeperServer server;
 
-    @Before
+    @BeforeEach
     public void setUp() throws Exception {
         super.setUp();
         server = serverFactory.getZooKeeperServer();
         zk = createClient();
     }
 
-    @After
+    @AfterEach
     public void tearDown() throws Exception {
         // server will be closed in super.tearDown
         super.tearDown();
@@ -86,7 +87,7 @@ public class TxnLogDigestTest extends ClientBase {
         ZooKeeperServer.setDigestEnabled(false);
     }
 
-    @BeforeClass
+    @BeforeAll
     public static void applyMockUps() {
         new MockedFileTxnLog();
     }
@@ -105,12 +106,12 @@ public class TxnLogDigestTest extends ClientBase {
         performOperations(createClient(), "/digestFromTxnLogsMatchesTree");
 
         // make sure there is no digest mismatch
-        Assert.assertEquals(0, digestMistachesCount.get());
+        assertEquals(0, digestMistachesCount.get());
 
         // verify that the digest is wrote to disk with txn
         TxnDigest lastDigest = getLastTxnLogDigest();
-        Assert.assertNotNull(lastDigest);
-        Assert.assertEquals(server.getZKDatabase().getDataTree().getTreeDigest(),
+        assertNotNull(lastDigest);
+        assertEquals(server.getZKDatabase().getDataTree().getTreeDigest(),
                 lastDigest.getTreeDigest());
     }
 
@@ -144,7 +145,7 @@ public class TxnLogDigestTest extends ClientBase {
         Map<String, String> expectedNodes1 = performOperations(createClient(), "/p2");
 
         // make sure there is no digest mismatch
-        Assert.assertEquals(0, digestMistachesCount.get());
+        assertEquals(0, digestMistachesCount.get());
 
         // 3. disable the digest again and make sure everything is fine
         restartServerWithDigestFlag(false);
@@ -179,7 +180,7 @@ public class TxnLogDigestTest extends ClientBase {
         restartServerWithDigestFlag(false);
 
         // check that no digest mismatch is reported
-        Assert.assertEquals(0, digestMistachesCount.get());
+        assertEquals(0, digestMistachesCount.get());
     }
 
     private void restartServerWithDigestFlag(boolean digestEnabled)
@@ -249,7 +250,7 @@ public class TxnLogDigestTest extends ClientBase {
         ZooKeeper client = createClient();
         try {
             for (Map.Entry<String, String> entry: expectedNodes.entrySet()) {
-                Assert.assertEquals(entry.getValue(),
+                assertEquals(entry.getValue(),
                         new String(client.getData(entry.getKey(), false, null)));
             }
         } finally {

+ 2 - 2
zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperCriticalThreadMetricsTest.java

@@ -18,14 +18,14 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import java.nio.ByteBuffer;
 import java.util.Map;
 import java.util.concurrent.CountDownLatch;
 import org.apache.zookeeper.ZKTestCase;
 import org.apache.zookeeper.ZooDefs;
 import org.apache.zookeeper.metrics.MetricsUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class ZooKeeperCriticalThreadMetricsTest extends ZKTestCase {
 

+ 8 - 8
zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java

@@ -18,9 +18,9 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.File;
 import java.io.IOException;
 import java.net.InetSocketAddress;
@@ -30,18 +30,18 @@ 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.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class ZooKeeperServerBeanTest {
 
-    @Before
+    @BeforeEach
     public void setup() {
         System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, "org.apache.zookeeper.server.NettyServerCnxnFactory");
     }
 
-    @After
+    @AfterEach
     public void teardown() throws Exception {
         System.clearProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
     }

+ 4 - 4
zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerConfTest.java

@@ -17,16 +17,16 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import java.util.Map;
 import org.apache.zookeeper.ZKTestCase;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class ZooKeeperServerConfTest extends ZKTestCase {
 
     private ZooKeeperServerConf c;
-    @Before
+    @BeforeEach
     public void setUp() {
         c = new ZooKeeperServerConf(1, "a", "b", 2, 3, 4, 5, 6L, 7);
     }

+ 1 - 1
zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerCreationTest.java

@@ -25,7 +25,7 @@ import org.apache.jute.BinaryOutputArchive;
 import org.apache.zookeeper.proto.ConnectRequest;
 import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class ZooKeeperServerCreationTest {
 

+ 57 - 67
zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerMainTest.java

@@ -19,11 +19,11 @@
 package org.apache.zookeeper.server;
 
 import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.File;
 import java.io.FileWriter;
 import java.io.IOException;
@@ -48,7 +48,8 @@ import org.apache.zookeeper.metrics.BaseTestMetricsProvider.MetricsProviderWithE
 import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
 import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -162,7 +163,8 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
      * Test to verify that even after non recoverable error (error while
      * writing transaction log), ZooKeeper is still available.
      */
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testNonRecoverableError() throws Exception {
         ClientBase.setupTestEnv();
 
@@ -171,9 +173,8 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         MainThread main = new MainThread(CLIENT_PORT, true, null);
         main.start();
 
-        assertTrue(
-                "waiting for server being up",
-                ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT),
+                "waiting for server being up");
 
         ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT, this);
 
@@ -200,9 +201,8 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
             // do nothing
         }
         zk.close();
-        assertTrue(
-                "waiting for server down",
-                ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT),
+                "waiting for server down");
         fileTxnSnapLogWithError.close();
         main.shutdown();
         main.deleteDirs();
@@ -214,7 +214,8 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
      *
      * This test will fail if it is executed as root user.
      */
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testReadOnlySnapshotDir() throws Exception {
         ClientBase.setupTestEnv();
         final int CLIENT_PORT = PortAssignment.unique();
@@ -224,9 +225,8 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         MainThread main = new MainThread(CLIENT_PORT, true, null);
         File tmpDir = main.tmpDir;
         main.start();
-        assertTrue(
-                "waiting for server being up",
-                ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT / 2));
+        assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT / 2),
+                "waiting for server being up");
         main.shutdown();
 
         // Make the snapshot directory read only
@@ -237,9 +237,8 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         main = new MainThread(CLIENT_PORT, false, tmpDir, null);
         main.start();
 
-        assertFalse(
-                "waiting for server being up",
-                ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT / 2));
+        assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT / 2),
+                "waiting for server being up");
 
         main.shutdown();
 
@@ -254,7 +253,8 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
      *
      * This test will fail if it is executed as root user.
      */
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testReadOnlyTxnLogDir() throws Exception {
         ClientBase.setupTestEnv();
         final int CLIENT_PORT = PortAssignment.unique();
@@ -264,9 +264,8 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         MainThread main = new MainThread(CLIENT_PORT, true, null);
         File tmpDir = main.tmpDir;
         main.start();
-        assertTrue(
-                "waiting for server being up",
-                ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT / 2));
+        assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT / 2),
+                "waiting for server being up");
         main.shutdown();
 
         // Make the transaction log directory read only
@@ -277,9 +276,8 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         main = new MainThread(CLIENT_PORT, false, tmpDir, null);
         main.start();
 
-        assertFalse(
-                "waiting for server being up",
-                ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT / 2));
+        assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT / 2),
+                "waiting for server being up");
 
         main.shutdown();
 
@@ -300,13 +298,12 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         MainThread main = new MainThread(CLIENT_PORT, true, null);
         main.start();
 
-        assertTrue(
-                "waiting for server being up",
-                ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT),
+                "waiting for server being up");
 
         clientConnected = new CountDownLatch(1);
         ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT, this);
-        assertTrue("Failed to establish zkclient connection!", clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+        assertTrue(clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS), "Failed to establish zkclient connection!");
 
         zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
@@ -316,9 +313,8 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         main.join();
         main.deleteDirs();
 
-        assertTrue(
-                "waiting for server down",
-                ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT),
+                "waiting for server down");
     }
 
     /**
@@ -425,13 +421,12 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         MainThread main = new MainThread(CLIENT_PORT, true, configs);
         main.start();
 
-        assertTrue(
-                "waiting for server being up",
-                ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT),
+                "waiting for server being up");
 
         clientConnected = new CountDownLatch(1);
         ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT, this);
-        assertTrue("Failed to establish zkclient connection!", clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+        assertTrue(clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS), "Failed to establish zkclient connection!");
 
         zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
@@ -441,9 +436,8 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         main.join();
         main.deleteDirs();
 
-        assertTrue(
-                "waiting for server down",
-                ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT),
+                "waiting for server down");
         assertTrue(MetricsProviderWithErrorInStop.stopCalled.get());
     }
 
@@ -463,13 +457,12 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         MainThread main = new MainThread(CLIENT_PORT, true, configs);
         main.start();
 
-        assertTrue(
-                "waiting for server being up",
-                ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT),
+                "waiting for server being up");
 
         clientConnected = new CountDownLatch(1);
         ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT, this);
-        assertTrue("Failed to establish zkclient connection!", clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+        assertTrue(clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS), "Failed to establish zkclient connection!");
 
         zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
@@ -479,9 +472,8 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         main.join();
         main.deleteDirs();
 
-        assertTrue(
-                "waiting for server down",
-                ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT),
+                "waiting for server down");
         assertEquals(1234, MetricsProviderWithConfiguration.httpPort.get());
     }
 
@@ -501,13 +493,12 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         MainThread main = new MainThread(CLIENT_PORT, true, configs);
         main.start();
 
-        assertTrue(
-                "waiting for server being up",
-                ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT),
+                "waiting for server being up");
 
         clientConnected = new CountDownLatch(1);
         ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT, this);
-        assertTrue("Failed to establish zkclient connection!", clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+        assertTrue(clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS), "Failed to establish zkclient connection!");
 
         zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
@@ -517,11 +508,11 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         main.join();
         main.deleteDirs();
 
-        assertTrue("waiting for server down", ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
-        assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.configureCalled.get());
-        assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.startCalled.get());
-        assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.getRootContextCalled.get());
-        assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.stopCalled.get());
+        assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT), "waiting for server down");
+        assertTrue(BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.configureCalled.get(), "metrics provider lifecycle error");
+        assertTrue(BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.startCalled.get(), "metrics provider lifecycle error");
+        assertTrue(BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.getRootContextCalled.get(), "metrics provider lifecycle error");
+        assertTrue(BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.stopCalled.get(), "metrics provider lifecycle error");
     }
 
     /**
@@ -541,7 +532,7 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         main.start();
 
         String HOSTPORT = "127.0.0.1:" + CLIENT_PORT;
-        assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT), "waiting for server being up");
         // create session with min value
         verifySessionTimeOut(minSessionTimeout, minSessionTimeout, HOSTPORT);
         verifySessionTimeOut(minSessionTimeout - 2000, minSessionTimeout, HOSTPORT);
@@ -549,7 +540,7 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         verifySessionTimeOut(maxSessionTimeout, maxSessionTimeout, HOSTPORT);
         verifySessionTimeOut(maxSessionTimeout + 2000, maxSessionTimeout, HOSTPORT);
         main.shutdown();
-        assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT), "waiting for server down");
     }
 
     /**
@@ -574,7 +565,7 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         main.start();
 
         String HOSTPORT = "127.0.0.1:" + CLIENT_PORT;
-        assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT), "waiting for server being up");
         // create session with min value
         verifySessionTimeOut(minSessionTimeout, minSessionTimeout, HOSTPORT);
         verifySessionTimeOut(minSessionTimeout - 2000, minSessionTimeout, HOSTPORT);
@@ -583,14 +574,14 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         verifySessionTimeOut(maxSessionTimeout + 2000, maxSessionTimeout, HOSTPORT);
         main.shutdown();
 
-        assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT), "waiting for server down");
     }
 
     private void verifySessionTimeOut(int sessionTimeout, int expectedSessionTimeout, String HOSTPORT) throws IOException, KeeperException, InterruptedException {
         clientConnected = new CountDownLatch(1);
         ZooKeeper zk = new ZooKeeper(HOSTPORT, sessionTimeout, this);
-        assertTrue("Failed to establish zkclient connection!", clientConnected.await(sessionTimeout, TimeUnit.MILLISECONDS));
-        assertEquals("Not able to configure the sessionTimeout values", expectedSessionTimeout, zk.getSessionTimeout());
+        assertTrue(clientConnected.await(sessionTimeout, TimeUnit.MILLISECONDS), "Failed to establish zkclient connection!");
+        assertEquals(expectedSessionTimeout, zk.getSessionTimeout(), "Not able to configure the sessionTimeout values");
         zk.close();
     }
 
@@ -655,10 +646,9 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
         ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
         ServerCnxnFactory f = ServerCnxnFactory.createFactory(CLIENT_PORT, -1);
         f.startup(zks);
-        assertNotNull("JMX initialization failed!", zks.jmxServerBean);
-        assertTrue(
-                "waiting for server being up",
-                ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
+        assertNotNull(zks.jmxServerBean, "JMX initialization failed!");
+        assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT),
+                "waiting for server being up");
         return f;
     }
 

+ 13 - 10
zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerMaxCnxnsTest.java

@@ -17,8 +17,9 @@
  */
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeoutException;
 import org.apache.zookeeper.CreateMode;
@@ -30,9 +31,9 @@ import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.server.quorum.QuorumPeerTestBase;
 import org.apache.zookeeper.test.ClientBase;
 import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -50,13 +51,15 @@ public class ZooKeeperServerMaxCnxnsTest extends QuorumPeerTestBase {
      * </pre>
      */
 
-    @Test(timeout = 120000)
+    @Test
+    @Timeout(value = 120)
     public void testMaxZooKeeperClientsWithNIOServerCnxnFactory() throws Exception {
         String serverCnxnFactory = "org.apache.zookeeper.server.NIOServerCnxnFactory";
         testMaxZooKeeperClients(serverCnxnFactory);
     }
 
-    @Test(timeout = 120000)
+    @Test
+    @Timeout(value = 120)
     public void testMaxZooKeeperClientsWithNettyServerCnxnFactory() throws Exception {
         String serverCnxnFactory = "org.apache.zookeeper.server.NettyServerCnxnFactory";
         testMaxZooKeeperClients(serverCnxnFactory);
@@ -87,8 +90,8 @@ public class ZooKeeperServerMaxCnxnsTest extends QuorumPeerTestBase {
 
         // ensure all servers started
         for (int i = 0; i < SERVER_COUNT; i++) {
-            Assert.assertTrue("waiting for server " + i + " being up", ClientBase
-                    .waitForServerUp("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT));
+            assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT),
+                    "waiting for server " + i + " being up");
         }
 
         int maxAllowedConnection = maxCnxns * SERVER_COUNT;
@@ -151,7 +154,7 @@ public class ZooKeeperServerMaxCnxnsTest extends QuorumPeerTestBase {
         return builder.toString();
     }
 
-    @After
+    @AfterEach
     public void tearDown() {
         // stop all clients
         if (clients != null) {

+ 24 - 18
zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerStartupTest.java

@@ -20,9 +20,9 @@ package org.apache.zookeeper.server;
 
 import static org.apache.zookeeper.client.FourLetterWordMain.send4LetterWord;
 import static org.apache.zookeeper.server.command.AbstractFourLetterCommand.ZK_NOT_SERVING;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.File;
 import java.io.IOException;
 import java.util.concurrent.CountDownLatch;
@@ -33,8 +33,9 @@ import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.common.X509Exception.SSLContextException;
 import org.apache.zookeeper.test.ClientBase;
 import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -53,7 +54,7 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
     private File tmpDir;
     private CountDownLatch startupDelayLatch = new CountDownLatch(1);
 
-    @After
+    @AfterEach
     public void teardown() throws Exception {
         // count down to avoid infinite blocking call due to this latch, if
         // any.
@@ -75,26 +76,29 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
      * Test case for
      * https://issues.apache.org/jira/browse/ZOOKEEPER-2383
      */
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testClientConnectionRequestDuringStartupWithNIOServerCnxn() throws Exception {
         tmpDir = ClientBase.createTmpDir();
         ClientBase.setupTestEnv();
 
         startSimpleZKServer(startupDelayLatch);
         SimpleZooKeeperServer simplezks = (SimpleZooKeeperServer) zks;
-        assertTrue("Failed to invoke zks#startup() method during server startup", simplezks.waitForStartupInvocation(10));
+        assertTrue(simplezks.waitForStartupInvocation(10), "Failed to invoke zks#startup() method during server startup");
 
         CountdownWatcher watcher = new CountdownWatcher();
         ZooKeeper zkClient = new ZooKeeper(HOSTPORT, ClientBase.CONNECTION_TIMEOUT, watcher);
 
-        assertFalse("Since server is not fully started, zks#createSession() shouldn't be invoked", simplezks.waitForSessionCreation(5));
+        assertFalse(simplezks.waitForSessionCreation(5),
+            "Since server is not fully started, zks#createSession() shouldn't be invoked");
 
         LOG.info("Decrements the count of the latch, so that server will proceed with startup");
         startupDelayLatch.countDown();
 
-        assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp(HOSTPORT, ClientBase.CONNECTION_TIMEOUT), "waiting for server being up ");
 
-        assertTrue("Failed to invoke zks#createSession() method during client session creation", simplezks.waitForSessionCreation(5));
+        assertTrue(simplezks.waitForSessionCreation(5),
+            "Failed to invoke zks#createSession() method during client session creation");
         watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
         zkClient.close();
     }
@@ -103,7 +107,8 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
      * Test case for
      * https://issues.apache.org/jira/browse/ZOOKEEPER-2383
      */
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testClientConnectionRequestDuringStartupWithNettyServerCnxn() throws Exception {
         tmpDir = ClientBase.createTmpDir();
         ClientBase.setupTestEnv();
@@ -113,19 +118,19 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
             System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, NettyServerCnxnFactory.class.getName());
             startSimpleZKServer(startupDelayLatch);
             SimpleZooKeeperServer simplezks = (SimpleZooKeeperServer) zks;
-            assertTrue("Failed to invoke zks#startup() method during server startup", simplezks.waitForStartupInvocation(10));
+            assertTrue(simplezks.waitForStartupInvocation(10), "Failed to invoke zks#startup() method during server startup");
 
             CountdownWatcher watcher = new CountdownWatcher();
             ZooKeeper zkClient = new ZooKeeper(HOSTPORT, ClientBase.CONNECTION_TIMEOUT, watcher);
 
-            assertFalse("Since server is not fully started, zks#createSession() shouldn't be invoked", simplezks.waitForSessionCreation(5));
+            assertFalse(simplezks.waitForSessionCreation(5), "Since server is not fully started, zks#createSession() shouldn't be invoked");
 
             LOG.info("Decrements the count of the latch, so that server will proceed with startup");
             startupDelayLatch.countDown();
 
-            assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
+            assertTrue(ClientBase.waitForServerUp(HOSTPORT, ClientBase.CONNECTION_TIMEOUT), "waiting for server being up ");
 
-            assertTrue("Failed to invoke zks#createSession() method during client session creation", simplezks.waitForSessionCreation(5));
+            assertTrue(simplezks.waitForSessionCreation(5), "Failed to invoke zks#createSession() method during client session creation");
             watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
             zkClient.close();
         } finally {
@@ -142,7 +147,8 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
      * Test case for
      * https://issues.apache.org/jira/browse/ZOOKEEPER-2383
      */
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testFourLetterWords() throws Exception {
         startSimpleZKServer(startupDelayLatch);
         verify("conf", ZK_NOT_SERVING);
@@ -162,7 +168,7 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
     private void verify(String cmd, String expected) throws IOException, SSLContextException {
         String resp = sendRequest(cmd);
         LOG.info("cmd {} expected {} got {}", cmd, expected, resp);
-        assertTrue("Unexpected response", resp.contains(expected));
+        assertTrue(resp.contains(expected), "Unexpected response");
     }
 
     private String sendRequest(String cmd) throws IOException, SSLContextException {

+ 6 - 6
zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerTest.java

@@ -18,9 +18,9 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.File;
 import java.io.IOException;
 import java.util.List;
@@ -29,7 +29,7 @@ import org.apache.zookeeper.server.persistence.FileTxnLog;
 import org.apache.zookeeper.server.persistence.SnapStream;
 import org.apache.zookeeper.server.persistence.Util;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class ZooKeeperServerTest extends ZKTestCase {
 
@@ -125,8 +125,8 @@ public class ZooKeeperServerTest extends ZKTestCase {
             if (!f.exists()) {
                 f.createNewFile();
             }
-            assertFalse("Snapshot file size is greater than 9 bytes", SnapStream.isValidSnapshot(f));
-            assertTrue("Can't delete file", f.delete());
+            assertFalse(SnapStream.isValidSnapshot(f), "Snapshot file size is greater than 9 bytes");
+            assertTrue(f.delete(), "Can't delete file");
         } catch (IOException e) {
         } finally {
             if (null != tmpFileDir) {

+ 7 - 5
zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperThreadTest.java

@@ -18,11 +18,12 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import org.apache.zookeeper.ZKTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
 
 public class ZooKeeperThreadTest extends ZKTestCase {
 
@@ -71,16 +72,17 @@ public class ZooKeeperThreadTest extends ZKTestCase {
     /**
      * Test verifies uncaught exception handling of ZooKeeperThread
      */
-    @Test(timeout = 30000)
+    @Test
+    @Timeout(value = 30)
     public void testUncaughtException() throws Exception {
         MyThread t1 = new MyThread("Test-Thread");
         t1.start();
-        assertTrue("Uncaught exception is not properly handled.", runningLatch.await(10000, TimeUnit.MILLISECONDS));
+        assertTrue(runningLatch.await(10000, TimeUnit.MILLISECONDS), "Uncaught exception is not properly handled.");
 
         runningLatch = new CountDownLatch(1);
         MyCriticalThread t2 = new MyCriticalThread("Test-Critical-Thread");
         t2.start();
-        assertTrue("Uncaught exception is not properly handled.", runningLatch.await(10000, TimeUnit.MILLISECONDS));
+        assertTrue(runningLatch.await(10000, TimeUnit.MILLISECONDS), "Uncaught exception is not properly handled.");
     }
 
 }

+ 14 - 16
zookeeper-server/src/test/java/org/apache/zookeeper/server/ZxidRolloverTest.java

@@ -18,10 +18,10 @@
 
 package org.apache.zookeeper.server;
 
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import org.apache.zookeeper.CreateMode;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.KeeperException.ConnectionLossException;
@@ -33,9 +33,9 @@ import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
 import org.apache.zookeeper.test.ClientTest;
 import org.apache.zookeeper.test.QuorumUtil;
 import org.apache.zookeeper.test.QuorumUtil.PeerStruct;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -57,7 +57,7 @@ public class ZxidRolloverTest extends ZKTestCase {
         return zkClients[idx - 1];
     }
 
-    @Before
+    @BeforeEach
     public void setUp() throws Exception {
         System.setProperty("zookeeper.admin.enableServer", "false");
 
@@ -117,9 +117,8 @@ public class ZxidRolloverTest extends ZKTestCase {
             // in the try, this catches that case and waits for the server
             // to come back
             PeerStruct peer = qu.getPeer(idx);
-            assertTrue(
-                    "Waiting for server down",
-                    ClientBase.waitForServerUp("127.0.0.1:" + peer.clientPort, ClientBase.CONNECTION_TIMEOUT));
+            assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + peer.clientPort, ClientBase.CONNECTION_TIMEOUT),
+                    "Waiting for server down");
 
             assertNull(zk.exists("/foofoofoo-connected", false));
         }
@@ -161,7 +160,7 @@ public class ZxidRolloverTest extends ZKTestCase {
     private void start(int idx) throws Exception {
         qu.start(idx);
         for (String hp : qu.getConnString().split(",")) {
-            assertTrue("waiting for server up", ClientBase.waitForServerUp(hp, ClientTest.CONNECTION_TIMEOUT));
+            assertTrue(ClientBase.waitForServerUp(hp, ClientTest.CONNECTION_TIMEOUT), "waiting for server up");
         }
 
         checkLeader();
@@ -190,9 +189,8 @@ public class ZxidRolloverTest extends ZKTestCase {
 
         // leader will shutdown, remaining followers will elect a new leader
         PeerStruct peer = qu.getPeer(idx);
-        assertTrue(
-                "Waiting for server down",
-                ClientBase.waitForServerDown("127.0.0.1:" + peer.clientPort, ClientBase.CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + peer.clientPort, ClientBase.CONNECTION_TIMEOUT),
+                "Waiting for server down");
 
         // if idx is the the leader then everyone will get disconnected,
         // otherwise if idx is a follower then just that client will get
@@ -215,7 +213,7 @@ public class ZxidRolloverTest extends ZKTestCase {
         zksLeader.setZxid((zksLeader.getZxid() & 0xffffffff00000000L) | 0xfffffffcL);
     }
 
-    @After
+    @AfterEach
     public void tearDown() throws Exception {
         LOG.info("tearDown starting");
         for (int i = 0; i < zkClients.length; i++) {

+ 4 - 4
zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandResponseTest.java

@@ -17,18 +17,18 @@
 
 package org.apache.zookeeper.server.admin;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import java.util.HashMap;
 import java.util.Map;
 import org.apache.zookeeper.ZKTestCase;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class CommandResponseTest extends ZKTestCase {
 
     private CommandResponse r;
 
-    @Before
+    @BeforeEach
     public void setUp() throws Exception {
         r = new CommandResponse("makemeasandwich", "makeityourself");
     }

+ 12 - 22
zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandsTest.java

@@ -18,11 +18,11 @@
 
 package org.apache.zookeeper.server.admin;
 
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 import java.io.IOException;
@@ -37,7 +37,7 @@ import org.apache.zookeeper.server.ZKDatabase;
 import org.apache.zookeeper.server.ZooKeeperServer;
 import org.apache.zookeeper.server.quorum.BufferStats;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 public class CommandsTest extends ClientBase {
 
@@ -63,30 +63,20 @@ public class CommandsTest extends ClientBase {
         // This is only true because we're setting cmdName to the primary name
         assertEquals(cmdName, result.remove("command"));
         assertTrue(result.containsKey("error"));
-        assertNull("error: " + result.get("error"), result.remove("error"));
+        assertNull(result.remove("error"), "error: " + result.get("error"));
 
         for (Field field : fields) {
             String k = field.key;
-            assertTrue("Result from command "
-                               + cmdName
-                               + " missing field \""
-                               + k
-                               + "\""
-                               + "\n"
-                               + result, result.containsKey(k));
+            assertTrue(result.containsKey(k),
+                    "Result from command " + cmdName + " missing field \"" + k + "\"" + "\n" + result);
             Class<?> t = field.type;
             Object v = result.remove(k);
-            assertTrue("\""
-                               + k
-                               + "\" field from command "
-                               + cmdName
-                               + " should be of type "
-                               + t
-                               + ", is actually of type "
-                               + v.getClass(), t.isAssignableFrom(v.getClass()));
+            assertTrue(t.isAssignableFrom(v.getClass()),
+                    "\"" + k + "\" field from command " + cmdName
+                            + " should be of type " + t + ", is actually of type " + v.getClass());
         }
 
-        assertTrue("Result from command " + cmdName + " contains extra fields: " + result, result.isEmpty());
+        assertTrue(result.isEmpty(), "Result from command " + cmdName + " contains extra fields: " + result);
     }
 
     public void testCommand(String cmdName, Field... fields) throws IOException, InterruptedException {

+ 20 - 26
zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/JettyAdminServerTest.java

@@ -18,8 +18,8 @@
 
 package org.apache.zookeeper.server.admin;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.BufferedReader;
 import java.io.File;
 import java.io.IOException;
@@ -46,9 +46,9 @@ import org.apache.zookeeper.server.admin.AdminServer.AdminServerException;
 import org.apache.zookeeper.server.quorum.QuorumPeerTestBase;
 import org.apache.zookeeper.test.ClientBase;
 import org.bouncycastle.jce.provider.BouncyCastleProvider;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -60,14 +60,14 @@ public class JettyAdminServerTest extends ZKTestCase {
     private static final String HTTPS_URL_FORMAT = "https://localhost:%d/commands";
     private static final int jettyAdminPort = PortAssignment.unique();
 
-    @Before
+    @BeforeEach
     public void enableServer() {
         // Override setting in ZKTestCase
         System.setProperty("zookeeper.admin.enableServer", "true");
         System.setProperty("zookeeper.admin.serverPort", "" + jettyAdminPort);
     }
 
-    @Before
+    @BeforeEach
     public void setupEncryption() {
         Security.addProvider(new BouncyCastleProvider());
         File tmpDir = null;
@@ -129,7 +129,7 @@ public class JettyAdminServerTest extends ZKTestCase {
         HttpsURLConnection.setDefaultHostnameVerifier(allValid);
     }
 
-    @After
+    @AfterEach
     public void cleanUp() {
         Security.removeProvider("BC");
 
@@ -172,17 +172,15 @@ public class JettyAdminServerTest extends ZKTestCase {
         ZooKeeperServerMainTest.MainThread main = new ZooKeeperServerMainTest.MainThread(CLIENT_PORT, false, null);
         main.start();
 
-        assertTrue(
-            "waiting for server being up",
-            ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT),
+                "waiting for server being up");
 
         queryAdminServer(jettyAdminPort);
 
         main.shutdown();
 
-        assertTrue(
-            "waiting for server down",
-            ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT),
+                "waiting for server down");
     }
 
     /**
@@ -219,12 +217,10 @@ public class JettyAdminServerTest extends ZKTestCase {
 
         Thread.sleep(500);
 
-        assertTrue(
-            "waiting for server 1 being up",
-            ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
-        assertTrue(
-            "waiting for server 2 being up",
-            ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT),
+                "waiting for server 1 being up");
+        assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT),
+                "waiting for server 2 being up");
 
         queryAdminServer(ADMIN_SERVER_PORT1);
         queryAdminServer(ADMIN_SERVER_PORT2);
@@ -232,12 +228,10 @@ public class JettyAdminServerTest extends ZKTestCase {
         q1.shutdown();
         q2.shutdown();
 
-        assertTrue(
-            "waiting for server 1 down",
-            ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
-        assertTrue(
-            "waiting for server 2 down",
-            ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT),
+                "waiting for server 1 down");
+        assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT),
+                "waiting for server 2 down");
     }
 
     /**

+ 27 - 27
zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxCounterSetTest.java

@@ -18,17 +18,17 @@
 
 package org.apache.zookeeper.server.metric;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import java.util.Map;
 import org.apache.zookeeper.ZKTestCase;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class AvgMinMaxCounterSetTest extends ZKTestCase {
 
     private AvgMinMaxCounterSet testCounterSet;
 
-    @Before
+    @BeforeEach
     public void initCounter() {
         testCounterSet = new AvgMinMaxCounterSet("test");
     }
@@ -49,19 +49,19 @@ public class AvgMinMaxCounterSetTest extends ZKTestCase {
 
         Map<String, Object> values = testCounterSet.values();
 
-        assertEquals("There should be 10 values in the set", 10, values.size());
+        assertEquals(10, values.size(), "There should be 10 values in the set");
 
-        assertEquals("avg_key1_test should =0", 0D, values.get("avg_key1_test"));
-        assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
-        assertEquals("max_key1_test should =0", 0L, values.get("max_key1_test"));
-        assertEquals("cnt_key1_test should =0", 0L, values.get("cnt_key1_test"));
-        assertEquals("sum_key1_test should =0", 0L, values.get("sum_key1_test"));
+        assertEquals(0D, values.get("avg_key1_test"), "avg_key1_test should =0");
+        assertEquals(0L, values.get("min_key1_test"), "min_key1_test should =0");
+        assertEquals(0L, values.get("max_key1_test"), "max_key1_test should =0");
+        assertEquals(0L, values.get("cnt_key1_test"), "cnt_key1_test should =0");
+        assertEquals(0L, values.get("sum_key1_test"), "sum_key1_test should =0");
 
-        assertEquals("avg_key2_test should =0", 0D, values.get("avg_key2_test"));
-        assertEquals("min_key2_test should =0", 0L, values.get("min_key2_test"));
-        assertEquals("max_key2_test should =0", 0L, values.get("max_key2_test"));
-        assertEquals("cnt_key2_test should =0", 0L, values.get("cnt_key2_test"));
-        assertEquals("sum_key2_test should =0", 0L, values.get("sum_key2_test"));
+        assertEquals(0D, values.get("avg_key2_test"), "avg_key2_test should =0");
+        assertEquals(0L, values.get("min_key2_test"), "min_key2_test should =0");
+        assertEquals(0L, values.get("max_key2_test"), "max_key2_test should =0");
+        assertEquals(0L, values.get("cnt_key2_test"), "cnt_key2_test should =0");
+        assertEquals(0L, values.get("sum_key2_test"), "sum_key2_test should =0");
 
     }
 
@@ -70,18 +70,18 @@ public class AvgMinMaxCounterSetTest extends ZKTestCase {
         addDataPoints();
         Map<String, Object> values = testCounterSet.values();
 
-        assertEquals("There should be 10 values in the set", 10, values.size());
-        assertEquals("avg_key1_test should =0.5", 0.5D, values.get("avg_key1_test"));
-        assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
-        assertEquals("max_key1_test should =1", 1L, values.get("max_key1_test"));
-        assertEquals("cnt_key1_test should =2", 2L, values.get("cnt_key1_test"));
-        assertEquals("sum_key1_test should =1", 1L, values.get("sum_key1_test"));
-
-        assertEquals("avg_key2_test should =3.5", 3.5, values.get("avg_key2_test"));
-        assertEquals("min_key2_test should =2", 2L, values.get("min_key2_test"));
-        assertEquals("max_key2_test should =5", 5L, values.get("max_key2_test"));
-        assertEquals("cnt_key2_test should =4", 4L, values.get("cnt_key2_test"));
-        assertEquals("sum_key2_test should =14", 14L, values.get("sum_key2_test"));
+        assertEquals(10, values.size(), "There should be 10 values in the set");
+        assertEquals(0.5D, values.get("avg_key1_test"), "avg_key1_test should =0.5");
+        assertEquals(0L, values.get("min_key1_test"), "min_key1_test should =0");
+        assertEquals(1L, values.get("max_key1_test"), "max_key1_test should =1");
+        assertEquals(2L, values.get("cnt_key1_test"), "cnt_key1_test should =2");
+        assertEquals(1L, values.get("sum_key1_test"), "sum_key1_test should =1");
+
+        assertEquals(3.5, values.get("avg_key2_test"), "avg_key2_test should =3.5");
+        assertEquals(2L, values.get("min_key2_test"), "min_key2_test should =2");
+        assertEquals(5L, values.get("max_key2_test"), "max_key2_test should =5");
+        assertEquals(4L, values.get("cnt_key2_test"), "cnt_key2_test should =4");
+        assertEquals(14L, values.get("sum_key2_test"), "sum_key2_test should =14");
     }
 
 }

+ 44 - 44
zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterSetTest.java

@@ -18,17 +18,17 @@
 
 package org.apache.zookeeper.server.metric;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import java.util.Map;
 import org.apache.zookeeper.ZKTestCase;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class AvgMinMaxPercentileCounterSetTest extends ZKTestCase {
 
     private AvgMinMaxPercentileCounterSet testCounterSet;
 
-    @Before
+    @BeforeEach
     public void initCounter() {
         testCounterSet = new AvgMinMaxPercentileCounterSet("test");
     }
@@ -50,25 +50,25 @@ public class AvgMinMaxPercentileCounterSetTest extends ZKTestCase {
 
         Map<String, Object> values = testCounterSet.values();
 
-        assertEquals("avg_key1_test should =0", 0D, values.get("avg_key1_test"));
-        assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
-        assertEquals("max_key1_test should =0", 0L, values.get("max_key1_test"));
-        assertEquals("cnt_key1_test should =0", 0L, values.get("cnt_key1_test"));
-        assertEquals("sum_key1_test should =0", 0L, values.get("sum_key1_test"));
-        assertEquals("p50_key1_test should have p50=0", 0L, values.get("p50_key1_test"));
-        assertEquals("p95_key1_test should have p95=0", 0L, values.get("p95_key1_test"));
-        assertEquals("p99_key1_test should have p99=0", 0L, values.get("p99_key1_test"));
-        assertEquals("p999_key1_test should have p999=0", 0L, values.get("p999_key1_test"));
-
-        assertEquals("avg_key2_test should =0", 0D, values.get("avg_key2_test"));
-        assertEquals("min_key2_test should =0", 0L, values.get("min_key2_test"));
-        assertEquals("max_key2_test should =0", 0L, values.get("max_key2_test"));
-        assertEquals("cnt_key2_test should =0", 0L, values.get("cnt_key2_test"));
-        assertEquals("sum_key2_test should =0", 0L, values.get("sum_key2_test"));
-        assertEquals("p50_key2_test should have p50=0", 0L, values.get("p50_key2_test"));
-        assertEquals("p95_key2_test should have p95=0", 0L, values.get("p95_key2_test"));
-        assertEquals("p99_key2_test should have p99=0", 0L, values.get("p99_key2_test"));
-        assertEquals("p999_key2_test should have p999=0", 0L, values.get("p999_key2_test"));
+        assertEquals(0D, values.get("avg_key1_test"), "avg_key1_test should =0");
+        assertEquals(0L, values.get("min_key1_test"), "min_key1_test should =0");
+        assertEquals(0L, values.get("max_key1_test"), "max_key1_test should =0");
+        assertEquals(0L, values.get("cnt_key1_test"), "cnt_key1_test should =0");
+        assertEquals(0L, values.get("sum_key1_test"), "sum_key1_test should =0");
+        assertEquals(0L, values.get("p50_key1_test"), "p50_key1_test should have p50=0");
+        assertEquals(0L, values.get("p95_key1_test"), "p95_key1_test should have p95=0");
+        assertEquals(0L, values.get("p99_key1_test"), "p99_key1_test should have p99=0");
+        assertEquals(0L, values.get("p999_key1_test"), "p999_key1_test should have p999=0");
+
+        assertEquals(0D, values.get("avg_key2_test"), "avg_key2_test should =0");
+        assertEquals(0L, values.get("min_key2_test"), "min_key2_test should =0");
+        assertEquals(0L, values.get("max_key2_test"), "max_key2_test should =0");
+        assertEquals(0L, values.get("cnt_key2_test"), "cnt_key2_test should =0");
+        assertEquals(0L, values.get("sum_key2_test"), "sum_key2_test should =0");
+        assertEquals(0L, values.get("p50_key2_test"), "p50_key2_test should have p50=0");
+        assertEquals(0L, values.get("p95_key2_test"), "p95_key2_test should have p95=0");
+        assertEquals(0L, values.get("p99_key2_test"), "p99_key2_test should have p99=0");
+        assertEquals(0L, values.get("p999_key2_test"), "p999_key2_test should have p999=0");
     }
 
     @Test
@@ -76,27 +76,27 @@ public class AvgMinMaxPercentileCounterSetTest extends ZKTestCase {
         addDataPoints();
         Map<String, Object> values = testCounterSet.values();
 
-        assertEquals("There should be 18 values in the set", 18, values.size());
-
-        assertEquals("avg_key1_test should =499.5", 999D / 2, values.get("avg_key1_test"));
-        assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
-        assertEquals("max_key1_test should =999", 999L, values.get("max_key1_test"));
-        assertEquals("cnt_key1_test should =1000", 1000L, values.get("cnt_key1_test"));
-        assertEquals("sum_key1_test should =999*500", 999 * 500L, values.get("sum_key1_test"));
-        assertEquals("p50_key1_test should have p50=500", 500L, values.get("p50_key1_test"));
-        assertEquals("p95_key1_test should have p95=950", 950L, values.get("p95_key1_test"));
-        assertEquals("p99_key1_test should have p99=990", 990L, values.get("p99_key1_test"));
-        assertEquals("p999_key1_test should have p999=999", 999L, values.get("p999_key1_test"));
-
-        assertEquals("avg_key2_test should =3.5", 1000 + 999D / 2, values.get("avg_key2_test"));
-        assertEquals("min_key2_test should =2", 1000L, values.get("min_key2_test"));
-        assertEquals("max_key2_test should =5", 1999L, values.get("max_key2_test"));
-        assertEquals("cnt_key2_test should =4", 1000L, values.get("cnt_key2_test"));
-        assertEquals("sum_key2_test should =14", 2999 * 500L, values.get("sum_key2_test"));
-        assertEquals("p50_key2_test should have p50=1500", 1500L, values.get("p50_key2_test"));
-        assertEquals("p95_key2_test should have p95=1950", 1950L, values.get("p95_key2_test"));
-        assertEquals("p99_key2_test should have p99=1990", 1990L, values.get("p99_key2_test"));
-        assertEquals("p999_key2_test should have p999=1999", 1999L, values.get("p999_key2_test"));
+        assertEquals(18, values.size(), "There should be 18 values in the set");
+
+        assertEquals(999D / 2, values.get("avg_key1_test"), "avg_key1_test should =499.5");
+        assertEquals(0L, values.get("min_key1_test"), "min_key1_test should =0");
+        assertEquals(999L, values.get("max_key1_test"), "max_key1_test should =999");
+        assertEquals(1000L, values.get("cnt_key1_test"), "cnt_key1_test should =1000");
+        assertEquals(999 * 500L, values.get("sum_key1_test"), "sum_key1_test should =999*500");
+        assertEquals(500L, values.get("p50_key1_test"), "p50_key1_test should have p50=500");
+        assertEquals(950L, values.get("p95_key1_test"), "p95_key1_test should have p95=950");
+        assertEquals(990L, values.get("p99_key1_test"), "p99_key1_test should have p99=990");
+        assertEquals(999L, values.get("p999_key1_test"), "p999_key1_test should have p999=999");
+
+        assertEquals(1000 + 999D / 2, values.get("avg_key2_test"), "avg_key2_test should =3.5");
+        assertEquals(1000L, values.get("min_key2_test"), "min_key2_test should =2");
+        assertEquals(1999L, values.get("max_key2_test"), "max_key2_test should =5");
+        assertEquals(1000L, values.get("cnt_key2_test"), "cnt_key2_test should =4");
+        assertEquals(2999 * 500L, values.get("sum_key2_test"), "sum_key2_test should =14");
+        assertEquals(1500L, values.get("p50_key2_test"), "p50_key2_test should have p50=1500");
+        assertEquals(1950L, values.get("p95_key2_test"), "p95_key2_test should have p95=1950");
+        assertEquals(1990L, values.get("p99_key2_test"), "p99_key2_test should have p99=1990");
+        assertEquals(1999L, values.get("p999_key2_test"), "p999_key2_test should have p999=1999");
     }
 
 }

+ 24 - 24
zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterTest.java

@@ -18,17 +18,17 @@
 
 package org.apache.zookeeper.server.metric;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import java.util.Map;
 import org.apache.zookeeper.ZKTestCase;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class AvgMinMaxPercentileCounterTest extends ZKTestCase {
 
     private AvgMinMaxPercentileCounter testCounter;
 
-    @Before
+    @BeforeEach
     public void initCounter() {
         testCounter = new AvgMinMaxPercentileCounter("test");
     }
@@ -46,17 +46,17 @@ public class AvgMinMaxPercentileCounterTest extends ZKTestCase {
 
         Map<String, Object> values = testCounter.values();
 
-        assertEquals("There should be 9 values in the set", 9, values.size());
+        assertEquals(9, values.size(), "There should be 9 values in the set");
 
-        assertEquals("should avg=0", 0D, values.get("avg_test"));
-        assertEquals("should have min=0", 0L, values.get("min_test"));
-        assertEquals("should have max=0", 0L, values.get("max_test"));
-        assertEquals("should have cnt=0", 0L, values.get("cnt_test"));
-        assertEquals("should have sum=0", 0L, values.get("sum_test"));
-        assertEquals("should have p50=0", 0L, values.get("p50_test"));
-        assertEquals("should have p95=0", 0L, values.get("p95_test"));
-        assertEquals("should have p99=0", 0L, values.get("p99_test"));
-        assertEquals("should have p999=0", 0L, values.get("p999_test"));
+        assertEquals(0D, values.get("avg_test"), "should avg=0");
+        assertEquals(0L, values.get("min_test"), "should have min=0");
+        assertEquals(0L, values.get("max_test"), "should have max=0");
+        assertEquals(0L, values.get("cnt_test"), "should have cnt=0");
+        assertEquals(0L, values.get("sum_test"), "should have sum=0");
+        assertEquals(0L, values.get("p50_test"), "should have p50=0");
+        assertEquals(0L, values.get("p95_test"), "should have p95=0");
+        assertEquals(0L, values.get("p99_test"), "should have p99=0");
+        assertEquals(0L, values.get("p999_test"), "should have p999=0");
     }
 
     @Test
@@ -64,17 +64,17 @@ public class AvgMinMaxPercentileCounterTest extends ZKTestCase {
         addDataPoints();
         Map<String, Object> values = testCounter.values();
 
-        assertEquals("There should be 9 values in the set", 9, values.size());
+        assertEquals(9, values.size(), "There should be 9 values in the set");
 
-        assertEquals("should avg=499.5", 999D / 2, values.get("avg_test"));
-        assertEquals("should have min=0", 0L, values.get("min_test"));
-        assertEquals("should have max=999", 999L, values.get("max_test"));
-        assertEquals("should have cnt=1000", 1000L, values.get("cnt_test"));
-        assertEquals("should have sum=999*500", 999 * 500L, values.get("sum_test"));
-        assertEquals("should have p50=500", 500L, values.get("p50_test"));
-        assertEquals("should have p95=950", 950L, values.get("p95_test"));
-        assertEquals("should have p99=990", 990L, values.get("p99_test"));
-        assertEquals("should have p999=999", 999L, values.get("p999_test"));
+        assertEquals(999D / 2, values.get("avg_test"), "should avg=499.5");
+        assertEquals(0L, values.get("min_test"), "should have min=0");
+        assertEquals(999L, values.get("max_test"), "should have max=999");
+        assertEquals(1000L, values.get("cnt_test"), "should have cnt=1000");
+        assertEquals(999 * 500L, values.get("sum_test"), "should have sum=999*500");
+        assertEquals(500L, values.get("p50_test"), "should have p50=500");
+        assertEquals(950L, values.get("p95_test"), "should have p95=950");
+        assertEquals(990L, values.get("p99_test"), "should have p99=990");
+        assertEquals(999L, values.get("p999_test"), "should have p999=999");
     }
 
 }

+ 5 - 5
zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/EmptySnapshotTest.java

@@ -18,16 +18,16 @@
 
 package org.apache.zookeeper.server.persistence;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.File;
 import java.io.IOException;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
 import org.apache.zookeeper.server.DataTree;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 
 /**
  * This test checks that the server does not create empty snapshot files if the

+ 22 - 38
zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnLogTest.java

@@ -18,12 +18,12 @@
 
 package org.apache.zookeeper.server.persistence;
 
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.core.Is.is;
 import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.Mockito.mock;
 import java.io.File;
 import java.io.IOException;
@@ -45,7 +45,7 @@ import org.apache.zookeeper.server.ZooKeeperServer;
 import org.apache.zookeeper.test.ClientBase;
 import org.apache.zookeeper.txn.CreateTxn;
 import org.apache.zookeeper.txn.TxnHeader;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -57,38 +57,28 @@ public class FileTxnLogTest extends ZKTestCase {
 
     @Test
     public void testInvalidPreallocSize() {
-        assertEquals(
-            "file should not be padded",
-            10 * KB,
-            FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, 0));
-        assertEquals(
-            "file should not be padded",
-            10 * KB,
-            FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, -1));
+        assertEquals(10 * KB, FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, 0),
+                "file should not be padded");
+        assertEquals(10 * KB, FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, -1),
+                "file should not be padded");
     }
 
     @Test
     public void testCalculateFileSizeWithPaddingWhenNotToCurrentSize() {
-        assertEquals(
-            "file should not be padded",
-            10 * KB,
-            FilePadding.calculateFileSizeWithPadding(5 * KB, 10 * KB, 10 * KB));
+        assertEquals(10 * KB, FilePadding.calculateFileSizeWithPadding(5 * KB, 10 * KB, 10 * KB),
+                "file should not be padded");
     }
 
     @Test
     public void testCalculateFileSizeWithPaddingWhenCloseToCurrentSize() {
-        assertEquals(
-            "file should be padded an additional 10 KB",
-            20 * KB,
-            FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, 10 * KB));
+        assertEquals(20 * KB, FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, 10 * KB),
+                "file should be padded an additional 10 KB");
     }
 
     @Test
     public void testFileSizeGreaterThanPosition() {
-        assertEquals(
-            "file should be padded to 40 KB",
-            40 * KB,
-            FilePadding.calculateFileSizeWithPadding(31 * KB, 10 * KB, 10 * KB));
+        assertEquals(40 * KB, FilePadding.calculateFileSizeWithPadding(31 * KB, 10 * KB, 10 * KB),
+                "file should be padded to 40 KB");
     }
 
     @Test
@@ -217,7 +207,7 @@ public class FileTxnLogTest extends ZKTestCase {
         final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
         ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
         f.startup(zks);
-        assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT), "waiting for server being up ");
         ZooKeeper zk = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, DummyWatcher.INSTANCE);
 
         // Generate transactions
@@ -245,25 +235,19 @@ public class FileTxnLogTest extends ZKTestCase {
 
         // shutdown
         f.shutdown();
-        assertTrue(
-            "waiting for server to shutdown",
-            ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
+        assertTrue(ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT), "waiting for server to shutdown");
 
         File logDir = new File(tmpDir, FileTxnSnapLog.version + FileTxnSnapLog.VERSION);
         File[] txnLogs = FileTxnLog.getLogFiles(logDir.listFiles(), 0);
 
-        assertEquals("Unexpected number of logs", 3, txnLogs.length);
+        assertEquals(3, txnLogs.length, "Unexpected number of logs");
 
         // Log size should not exceed limit by more than one node size;
         long threshold = LOG_SIZE_LIMIT + NODE_SIZE;
         LOG.info(txnLogs[0].getAbsolutePath());
-        assertTrue(
-            "Exceed log size limit: " + txnLogs[0].length(),
-            threshold > txnLogs[0].length());
+        assertTrue(threshold > txnLogs[0].length(), "Exceed log size limit: " + txnLogs[0].length());
         LOG.info(txnLogs[1].getAbsolutePath());
-        assertTrue(
-            "Exceed log size limit " + txnLogs[1].length(),
-            threshold > txnLogs[1].length());
+        assertTrue(threshold > txnLogs[1].length(), "Exceed log size limit " + txnLogs[1].length());
 
         // Start database only
         zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
@@ -274,8 +258,8 @@ public class FileTxnLogTest extends ZKTestCase {
         for (long i = 0; i < txnCount; i++) {
             Stat stat = new Stat();
             byte[] data = db.getData("/node-" + i, stat, null);
-            assertArrayEquals("Missmatch data", bytes, data);
-            assertTrue("Unknown zxid ", zxids.contains(stat.getMzxid()));
+            assertArrayEquals(bytes, data, "Missmatch data");
+            assertTrue(zxids.contains(stat.getMzxid()), "Unknown zxid ");
         }
     }
 

+ 3 - 3
zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogMetricsTest.java

@@ -18,10 +18,10 @@
 
 package org.apache.zookeeper.server.persistence;
 
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.number.OrderingComparison.greaterThan;
 import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import java.util.Map;
 import java.util.concurrent.CountDownLatch;
 import org.apache.zookeeper.CreateMode;
@@ -35,7 +35,7 @@ import org.apache.zookeeper.server.ServerMetrics;
 import org.apache.zookeeper.server.SyncRequestProcessor;
 import org.apache.zookeeper.test.ClientBase;
 import org.apache.zookeeper.test.QuorumUtil;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 

+ 52 - 45
zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogTest.java

@@ -18,13 +18,14 @@
 
 package org.apache.zookeeper.server.persistence;
 
-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.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
@@ -47,9 +48,9 @@ import org.apache.zookeeper.txn.CreateTxn;
 import org.apache.zookeeper.txn.SetDataTxn;
 import org.apache.zookeeper.txn.TxnDigest;
 import org.apache.zookeeper.txn.TxnHeader;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class FileTxnSnapLogTest {
 
@@ -63,14 +64,14 @@ public class FileTxnSnapLogTest {
 
     private File snapVersionDir;
 
-    @Before
+    @BeforeEach
     public void setUp() throws Exception {
         tmpDir = ClientBase.createEmptyTestDir();
         logDir = new File(tmpDir, "logdir");
         snapDir = new File(tmpDir, "snapdir");
     }
 
-    @After
+    @AfterEach
     public void tearDown() throws Exception {
         if (tmpDir != null) {
             TestUtils.deleteFileRecursively(tmpDir);
@@ -169,8 +170,8 @@ public class FileTxnSnapLogTest {
      */
     @Test
     public void testWithAutoCreateDataDir() throws IOException {
-        assertFalse("log directory already exists", logDir.exists());
-        assertFalse("snapshot directory already exists", snapDir.exists());
+        assertFalse(logDir.exists(), "log directory already exists");
+        assertFalse(snapDir.exists(), "snapshot directory already exists");
 
         FileTxnSnapLog fileTxnSnapLog = createFileTxnSnapLogWithAutoCreateDataDir(logDir, snapDir, "true");
 
@@ -184,20 +185,22 @@ public class FileTxnSnapLogTest {
      * Test verifies server should fail when log dir or snap dir doesn't exist.
      * Sets "zookeeper.datadir.autocreate" to false.
      */
-    @Test(expected = FileTxnSnapLog.DatadirException.class)
+    @Test
     public void testWithoutAutoCreateDataDir() throws Exception {
-        assertFalse("log directory already exists", logDir.exists());
-        assertFalse("snapshot directory already exists", snapDir.exists());
-
-        try {
-            createFileTxnSnapLogWithAutoCreateDataDir(logDir, snapDir, "false");
-        } catch (FileTxnSnapLog.DatadirException e) {
-            assertFalse(logDir.exists());
-            assertFalse(snapDir.exists());
-            // rethrow exception
-            throw e;
-        }
-        fail("Expected exception from FileTxnSnapLog");
+        assertThrows(FileTxnSnapLog.DatadirException.class, () -> {
+            assertFalse(logDir.exists(), "log directory already exists");
+            assertFalse(snapDir.exists(), "snapshot directory already exists");
+
+            try {
+                createFileTxnSnapLogWithAutoCreateDataDir(logDir, snapDir, "false");
+            } catch (FileTxnSnapLog.DatadirException e) {
+                assertFalse(logDir.exists());
+                assertFalse(snapDir.exists());
+                // rethrow exception
+                throw e;
+            }
+            fail("Expected exception from FileTxnSnapLog");
+        });
     }
 
     private void attemptAutoCreateDB(
@@ -216,22 +219,22 @@ public class FileTxnSnapLogTest {
                 // empty by default
             }
         });
-        assertEquals("unexpected zxid", expectedValue, zxid);
+        assertEquals(expectedValue, zxid, "unexpected zxid");
     }
 
     @Test
     public void testAutoCreateDB() throws IOException {
-        assertTrue("cannot create log directory", logDir.mkdir());
-        assertTrue("cannot create snapshot directory", snapDir.mkdir());
+        assertTrue(logDir.mkdir(), "cannot create log directory");
+        assertTrue(snapDir.mkdir(), "cannot create snapshot directory");
         File initFile = new File(logDir, "initialize");
-        assertFalse("initialize file already exists", initFile.exists());
+        assertFalse(initFile.exists(), "initialize file already exists");
 
         Map<Long, Integer> sessions = new ConcurrentHashMap<>();
 
         attemptAutoCreateDB(logDir, snapDir, sessions, "false", -1L);
         attemptAutoCreateDB(logDir, snapDir, sessions, "true", 0L);
 
-        assertTrue("cannot create initialize file", initFile.createNewFile());
+        assertTrue(initFile.createNewFile(), "cannot create initialize file");
         attemptAutoCreateDB(logDir, snapDir, sessions, "false", 0L);
     }
 
@@ -247,7 +250,7 @@ public class FileTxnSnapLogTest {
             fileTxnSnapLog.append(req);
             fileTxnSnapLog.commit();
             long syncElapsedTime = fileTxnSnapLog.getTxnLogElapsedSyncTime();
-            assertNotEquals("Did not update syncElapsedTime!", -1L, syncElapsedTime);
+            assertNotEquals(-1L, syncElapsedTime, "Did not update syncElapsedTime!");
         } finally {
             fileTxnSnapLog.close();
         }
@@ -275,26 +278,30 @@ public class FileTxnSnapLogTest {
         }
     }
 
-    @Test(expected = FileTxnSnapLog.LogDirContentCheckException.class)
+    @Test
     public void testDirCheckWithSnapFilesInLogDir() throws IOException {
-        twoDirSetupWithCorrectFiles();
+        assertThrows(FileTxnSnapLog.LogDirContentCheckException.class, () -> {
+            twoDirSetupWithCorrectFiles();
 
-        // add snapshot files to the log version dir
-        createSnapshotFile(logVersionDir, 3);
-        createSnapshotFile(logVersionDir, 4);
+            // add snapshot files to the log version dir
+            createSnapshotFile(logVersionDir, 3);
+            createSnapshotFile(logVersionDir, 4);
 
-        createFileTxnSnapLogWithNoAutoCreateDataDir(logDir, snapDir);
+            createFileTxnSnapLogWithNoAutoCreateDataDir(logDir, snapDir);
+        });
     }
 
-    @Test(expected = FileTxnSnapLog.SnapDirContentCheckException.class)
+    @Test
     public void testDirCheckWithLogFilesInSnapDir() throws IOException {
-        twoDirSetupWithCorrectFiles();
+        assertThrows(FileTxnSnapLog.SnapDirContentCheckException.class, () -> {
+            twoDirSetupWithCorrectFiles();
 
-        // add transaction log files to the snap version dir
-        createLogFile(snapVersionDir, 3);
-        createLogFile(snapVersionDir, 4);
+            // add transaction log files to the snap version dir
+            createLogFile(snapVersionDir, 3);
+            createLogFile(snapVersionDir, 4);
 
-        createFileTxnSnapLogWithNoAutoCreateDataDir(logDir, snapDir);
+            createFileTxnSnapLogWithNoAutoCreateDataDir(logDir, snapDir);
+        });
     }
 
     /**

+ 10 - 10
zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/SnapStreamTest.java

@@ -19,9 +19,9 @@
 package org.apache.zookeeper.server.persistence;
 
 import static org.apache.zookeeper.test.ClientBase.createTmpDir;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.File;
 import java.io.IOException;
 import java.io.OutputStream;
@@ -32,12 +32,12 @@ import org.apache.jute.BinaryOutputArchive;
 import org.apache.jute.InputArchive;
 import org.apache.jute.OutputArchive;
 import org.apache.zookeeper.server.persistence.SnapStream.StreamMode;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
 
 public class SnapStreamTest {
 
-    @After
+    @AfterEach
     public void tearDown() {
         System.clearProperty(SnapStream.ZOOKEEPER_SHAPSHOT_STREAM_MODE);
         SnapStream.setStreamMode(StreamMode.DEFAULT_MODE);
@@ -58,9 +58,9 @@ public class SnapStreamTest {
 
     @Test
     public void testGetStreamMode() {
-        assertEquals("expected to return un-compressed stream", StreamMode.CHECKED, SnapStream.getStreamMode("snapshot.180000e3a2"));
-        assertEquals("expected to return snappy stream", StreamMode.SNAPPY, SnapStream.getStreamMode("snapshot.180000e3a2.snappy"));
-        assertEquals("expected to return gzip stream", StreamMode.GZIP, SnapStream.getStreamMode("snapshot.180000e3a2.gz"));
+        assertEquals(StreamMode.CHECKED, SnapStream.getStreamMode("snapshot.180000e3a2"), "expected to return un-compressed stream");
+        assertEquals(StreamMode.SNAPPY, SnapStream.getStreamMode("snapshot.180000e3a2.snappy"), "expected to return snappy stream");
+        assertEquals(StreamMode.GZIP, SnapStream.getStreamMode("snapshot.180000e3a2.gz"), "expected to return gzip stream");
     }
 
     @Test
@@ -104,7 +104,7 @@ public class SnapStreamTest {
         InputArchive ia = BinaryInputArchive.getArchive(is);
         FileHeader restoredHeader = new FileHeader();
         restoredHeader.deserialize(ia, "fileheader");
-        assertEquals("magic not the same", restoredHeader, header);
+        assertEquals(restoredHeader, header, "magic not the same");
         SnapStream.checkSealIntegrity(is, ia);
     }
 

+ 24 - 19
zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/TxnLogToolkitTest.java

@@ -19,9 +19,10 @@
 package org.apache.zookeeper.server.persistence;
 
 import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.core.IsNot.not;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileNotFoundException;
@@ -32,9 +33,9 @@ import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import org.apache.commons.io.FileUtils;
 import org.apache.zookeeper.test.ClientBase;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
 
 public class TxnLogToolkitTest {
 
@@ -44,7 +45,7 @@ public class TxnLogToolkitTest {
     private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
     private File mySnapDir;
 
-    @Before
+    @BeforeEach
     public void setUp() throws IOException {
         System.setOut(new PrintStream(outContent));
         System.setErr(new PrintStream(errContent));
@@ -53,7 +54,7 @@ public class TxnLogToolkitTest {
         FileUtils.copyDirectory(snapDir, mySnapDir);
     }
 
-    @After
+    @AfterEach
     public void tearDown() throws IOException {
         System.setOut(System.out);
         System.setErr(System.err);
@@ -74,20 +75,24 @@ public class TxnLogToolkitTest {
         // no exception thrown
     }
 
-    @Test(expected = TxnLogToolkit.TxnLogToolkitException.class)
+    @Test
     public void testInitMissingFile() throws FileNotFoundException, TxnLogToolkit.TxnLogToolkitException {
-        // Arrange & Act
-        File logfile = new File("this_file_should_not_exists");
-        TxnLogToolkit lt = new TxnLogToolkit(false, false, logfile.toString(), true);
+        assertThrows(TxnLogToolkit.TxnLogToolkitException.class, () -> {
+            // Arrange & Act
+            File logfile = new File("this_file_should_not_exists");
+            TxnLogToolkit lt = new TxnLogToolkit(false, false, logfile.toString(), true);
+        });
     }
 
-    @Test(expected = TxnLogToolkit.TxnLogToolkitException.class)
-    public void testInitWithRecoveryFileExists() throws IOException, TxnLogToolkit.TxnLogToolkitException {
-        // Arrange & Act
-        File logfile = new File(new File(mySnapDir, "version-2"), "log.274");
-        File recoveryFile = new File(new File(mySnapDir, "version-2"), "log.274.fixed");
-        recoveryFile.createNewFile();
-        TxnLogToolkit lt = new TxnLogToolkit(true, false, logfile.toString(), true);
+    @Test
+    public void testInitWithRecoveryFileExists() {
+        assertThrows(TxnLogToolkit.TxnLogToolkitException.class, () -> {
+            // Arrange & Act
+            File logfile = new File(new File(mySnapDir, "version-2"), "log.274");
+            File recoveryFile = new File(new File(mySnapDir, "version-2"), "log.274.fixed");
+            recoveryFile.createNewFile();
+            TxnLogToolkit lt = new TxnLogToolkit(true, false, logfile.toString(), true);
+        });
     }
 
     @Test
@@ -103,7 +108,7 @@ public class TxnLogToolkitTest {
         String output = outContent.toString();
         Pattern p = Pattern.compile("^CRC ERROR.*session 0x8061fac5ddeb0000 cxid 0x0 zxid 0x8800000002 createSession 30000$", Pattern.MULTILINE);
         Matcher m = p.matcher(output);
-        assertTrue("Output doesn't indicate CRC error for the broken session id: " + output, m.find());
+        assertTrue(m.find(), "Output doesn't indicate CRC error for the broken session id: " + output);
     }
 
     @Test

+ 2 - 2
zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/BufferStatsTest.java

@@ -18,8 +18,8 @@
 
 package org.apache.zookeeper.server.quorum;
 
-import static org.junit.Assert.assertEquals;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import org.junit.jupiter.api.Test;
 
 public class BufferStatsTest {
 

Một số tệp đã không được hiển thị bởi vì quá nhiều tập tin thay đổi trong này khác