You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by kl...@apache.org on 2017/01/10 22:27:13 UTC

[1/8] geode git commit: Convert from ManagementTestCase to ManagementTestRule

Repository: geode
Updated Branches:
  refs/heads/feature/GEODE-1930-2 [created] a409b5a2e


http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/management/LuceneManagementDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/management/LuceneManagementDUnitTest.java b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/management/LuceneManagementDUnitTest.java
index ef4681c..b3d4814 100644
--- a/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/management/LuceneManagementDUnitTest.java
+++ b/geode-lucene/src/test/java/org/apache/geode/cache/lucene/internal/management/LuceneManagementDUnitTest.java
@@ -144,13 +144,13 @@ public class LuceneManagementDUnitTest extends ManagementTestBase {
     }
   }
 
-  private static void verifyMBean() {
+  private void verifyMBean() {
     getMBean();
   }
 
-  private static LuceneServiceMXBean getMBean() {
-    ObjectName objectName =
-        MBeanJMXAdapter.getCacheServiceMBeanName(ds.getDistributedMember(), "LuceneService");
+  private LuceneServiceMXBean getMBean() {
+    ObjectName objectName = MBeanJMXAdapter
+        .getCacheServiceMBeanName(getSystem().getDistributedMember(), "LuceneService");
     assertNotNull(getManagementService().getMBeanInstance(objectName, LuceneServiceMXBean.class));
     return getManagementService().getMBeanInstance(objectName, LuceneServiceMXBean.class);
   }
@@ -179,14 +179,14 @@ public class LuceneManagementDUnitTest extends ManagementTestBase {
     createPartitionRegion(vm, regionName);
   }
 
-  private static void createIndexes(String regionName, int numIndexes) {
-    LuceneService luceneService = LuceneServiceProvider.get(cache);
+  private void createIndexes(String regionName, int numIndexes) {
+    LuceneService luceneService = LuceneServiceProvider.get(getCache());
     for (int i = 0; i < numIndexes; i++) {
       luceneService.createIndex(INDEX_NAME + "_" + i, regionName, "field" + i);
     }
   }
 
-  private static void verifyAllMBeanIndexMetrics(String regionName, int numRegionIndexes,
+  private void verifyAllMBeanIndexMetrics(String regionName, int numRegionIndexes,
       int numTotalIndexes) {
     LuceneServiceMXBean mbean = getMBean();
     verifyMBeanIndexMetrics(mbean, regionName, numRegionIndexes, numTotalIndexes);
@@ -211,18 +211,17 @@ public class LuceneManagementDUnitTest extends ManagementTestBase {
     }
   }
 
-  private static void putEntries(String regionName, int numEntries) {
+  private void putEntries(String regionName, int numEntries) {
     for (int i = 0; i < numEntries; i++) {
-      Region region = cache.getRegion(regionName);
+      Region region = getCache().getRegion(regionName);
       String key = String.valueOf(i);
       Object value = new TestObject(key);
       region.put(key, value);
     }
   }
 
-  private static void queryEntries(String regionName, String indexName)
-      throws LuceneQueryException {
-    LuceneService service = LuceneServiceProvider.get(cache);
+  private void queryEntries(String regionName, String indexName) throws LuceneQueryException {
+    LuceneService service = LuceneServiceProvider.get(getCache());
     LuceneQuery query =
         service.createLuceneQueryFactory().create(indexName, regionName, "field0:0", null);
     query.findValues();

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/gradle/dependency-versions.properties
----------------------------------------------------------------------
diff --git a/gradle/dependency-versions.properties b/gradle/dependency-versions.properties
index 828b088..05d7124 100644
--- a/gradle/dependency-versions.properties
+++ b/gradle/dependency-versions.properties
@@ -68,7 +68,8 @@ jline.version = 2.12
 jmock.version = 2.8.2
 jna.version = 4.0.0
 jopt-simple.version = 5.0.1
-json-path.version = 1.2.0
+json-path.version = 2.2.0
+json-path-assert.version = 2.2.0
 json4s.version = 3.2.4
 jsr305.version = 3.0.1
 junit.version = 4.12


[3/8] geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/RegionManagementDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/RegionManagementDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/RegionManagementDUnitTest.java
index fcdc3a4..3dc92b6 100644
--- a/geode-core/src/test/java/org/apache/geode/management/RegionManagementDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/RegionManagementDUnitTest.java
@@ -12,22 +12,44 @@
  * or implied. See the License for the specific language governing permissions and limitations under
  * the License.
  */
+/*
+ * 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.geode.management;
 
-import static org.junit.Assert.*;
+import static java.util.concurrent.TimeUnit.MINUTES;
+import static org.apache.geode.cache.Region.*;
+import static org.apache.geode.test.dunit.Host.*;
+import static org.apache.geode.test.dunit.Invoke.invokeInEveryVM;
+import static org.assertj.core.api.Assertions.*;
 
+import java.lang.management.ManagementFactory;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
 
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanServer;
-import javax.management.MalformedObjectNameException;
 import javax.management.Notification;
 import javax.management.NotificationListener;
 import javax.management.ObjectName;
 
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
+import org.junit.After;
+import org.junit.Before;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
@@ -41,1325 +63,1156 @@ import org.apache.geode.cache.PartitionAttributes;
 import org.apache.geode.cache.PartitionAttributesFactory;
 import org.apache.geode.cache.Region;
 import org.apache.geode.cache.RegionAttributes;
+import org.apache.geode.cache.RegionFactory;
+import org.apache.geode.cache.RegionShortcut;
 import org.apache.geode.cache.Scope;
 import org.apache.geode.cache.query.data.Portfolio;
 import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.InternalDistributedSystem;
+import org.apache.geode.distributed.internal.DM;
+import org.apache.geode.internal.cache.AbstractRegion;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.cache.LocalRegion;
 import org.apache.geode.internal.cache.TestObjectSizerImpl;
 import org.apache.geode.internal.cache.lru.LRUStatistics;
 import org.apache.geode.internal.cache.partitioned.fixed.SingleHopQuarterPartitionResolver;
 import org.apache.geode.management.internal.MBeanJMXAdapter;
 import org.apache.geode.management.internal.SystemManagementService;
-import org.apache.geode.test.dunit.Assert;
 import org.apache.geode.test.dunit.LogWriterUtils;
-import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.dunit.Wait;
 import org.apache.geode.test.dunit.WaitCriterion;
 import org.apache.geode.test.junit.categories.DistributedTest;
-import org.apache.geode.test.junit.categories.FlakyTest;
 
 /**
  * This class checks and verifies various data and operations exposed through RegionMXBean
  * interface.
- * 
+ * <p>
  * Goal of the Test : RegionMBean gets created once region is created. Data like Region Attributes
  * data and stats are of proper value
- * 
- * 
  */
 @Category(DistributedTest.class)
+@SuppressWarnings({"serial", "unused"})
 public class RegionManagementDUnitTest extends ManagementTestBase {
 
-  private static final long serialVersionUID = 1L;
-
-  private final String VERIFY_CONFIG_METHOD = "verifyConfigData";
+  private static final String REGION_NAME = "MANAGEMENT_TEST_REGION";
+  private static final String PARTITIONED_REGION_NAME = "MANAGEMENT_PAR_REGION";
+  private static final String FIXED_PR_NAME = "MANAGEMENT_FIXED_PR";
+  private static final String LOCAL_REGION_NAME = "TEST_LOCAL_REGION";
+  private static final String LOCAL_SUB_REGION_NAME = "TEST_LOCAL_SUB_REGION";
 
-  private final String VERIFY_REMOTE_CONFIG_METHOD = "verifyConfigDataRemote";
+  private static final String REGION_PATH = SEPARATOR + REGION_NAME;
+  private static final String PARTITIONED_REGION_PATH = SEPARATOR + PARTITIONED_REGION_NAME;
+  private static final String FIXED_PR_PATH = SEPARATOR + FIXED_PR_NAME;
+  private static final String LOCAL_SUB_REGION_PATH =
+      SEPARATOR + LOCAL_REGION_NAME + SEPARATOR + LOCAL_SUB_REGION_NAME;
 
-  static final String REGION_NAME = "MANAGEMENT_TEST_REGION";
+  // field used in manager VM
+  private static Region fixedPartitionedRegion;
 
-  static final String PARTITIONED_REGION_NAME = "MANAGEMENT_PAR_REGION";
+  private static final AtomicReference<List<Notification>> MEMBER_NOTIFICATIONS_REF =
+      new AtomicReference<>();
+  private static final AtomicReference<List<Notification>> SYSTEM_NOTIFICATIONS_REF =
+      new AtomicReference<>();
 
-  static final String FIXED_PR_NAME = "MANAGEMENT_FIXED_PR";
+  @Manager
+  private VM managerVM;
 
-  static final String REGION_PATH = "/MANAGEMENT_TEST_REGION";
+  @Member
+  private VM[] memberVMs;
 
-  static final String PARTITIONED_REGION_PATH = "/MANAGEMENT_PAR_REGION";
+  @Before
+  public void before() throws Exception {
+    this.managerVM = getHost(0).getVM(0);
 
-  static final String FIXED_PR_PATH = "/MANAGEMENT_FIXED_PR";
-
-  static final String LOCAL_REGION_NAME = "TEST_LOCAL_REGION";
-  static final String LOCAL_SUB_REGION_NAME = "TEST_LOCAL_SUB_REGION";
-  static final String LOCAL_REGION_PATH = "/TEST_LOCAL_REGION";
-  static final String LOCAL_SUB_REGION_PATH = "/TEST_LOCAL_REGION/TEST_LOCAL_SUB_REGION";
-
-  private static final int MAX_WAIT = 70 * 1000;
-
-  protected static final Region DiskRegion = null;
+    this.memberVMs = new VM[3];
+    this.memberVMs[0] = getHost(0).getVM(1);
+    this.memberVMs[1] = getHost(0).getVM(2);
+    this.memberVMs[2] = getHost(0).getVM(3);
+  }
 
-  static List<FixedPartitionAttributes> fpaList = new ArrayList<FixedPartitionAttributes>();
+  @After
+  public void after() throws Exception {
+    invokeInEveryVM(() -> MEMBER_NOTIFICATIONS_REF.set(null));
+    invokeInEveryVM(() -> SYSTEM_NOTIFICATIONS_REF.set(null));
+    disconnectAllFromDS_tmp();
+  }
 
+  private void createMembersAndThenManagers_tmp() throws Exception {
+    initManagement(false);
+  }
 
-  private static Region fixedPrRegion;
+  private void createManagersAndThenMembers_tmp() throws Exception {
+    initManagement(true);
+  }
 
+  private void disconnectAllFromDS_tmp() {
+    disconnectAllFromDS();
+  }
 
-  public RegionManagementDUnitTest() {
-    super();
+  private ManagementService getManagementService_tmp() {
+    return getManagementService();
+  }
 
+  private Cache getCache_tmp() {
+    return getCache();
   }
 
   /**
    * Tests all Region MBean related Management APIs
-   * 
+   * <p>
    * a) Notification propagated to member MBean while a region is created
-   * 
+   * <p>
    * b) Creates and check a Distributed Region
-   * 
-   * 
-   * @throws Exception
    */
-
-  @Category(FlakyTest.class) // GEODE-1538
   @Test
   public void testDistributedRegion() throws Exception {
+    createMembersAndThenManagers_tmp();
 
-    initManagement(false);
-
-
-    VM[] managedNodes = new VM[getManagedNodeList().size()];
-
-    getManagedNodeList().toArray(managedNodes);
-    // Adding notif listener for remote cache members
-    addMemberListener(managingNode);
-
-    for (int j = 0; j < managedNodes.length; j++) {
-
-      VM vm = managedNodes[j];
-
-      createDistributedRegion(vm, REGION_NAME);
-      validateReplicateRegionAfterCreate(vm);
+    // Adding notification listener for remote cache memberVMs
+    addMemberNotificationListener(this.managerVM, 3); // TODO: why?
 
+    for (VM memberVM : this.memberVMs) {
+      createDistributedRegion_tmp(memberVM, REGION_NAME);
+      verifyReplicateRegionAfterCreate(memberVM);
     }
 
-    verifyRemoteDistributedRegion(managingNode, 3);
-
+    verifyRemoteDistributedRegion(this.managerVM, 3);
 
-    for (VM vm : getManagedNodeList()) {
-      closeRegion(vm, REGION_PATH);
-      validateReplicatedRegionAfterClose(vm);
+    for (VM memberVM : this.memberVMs) {
+      closeRegion(memberVM, REGION_PATH);
+      verifyReplicatedRegionAfterClose(memberVM);
     }
 
-    ensureProxyCleanup(managingNode);
+    verifyProxyCleanup(this.managerVM);
+
+    verifyMemberNotifications(this.managerVM, REGION_NAME, 3);
   }
 
   /**
    * Tests all Region MBean related Management APIs
-   * 
+   * <p>
    * a) Notification propagated to member MBean while a region is created
-   * 
+   * <p>
    * b) Created and check a Partitioned Region
-   * 
-   * @throws Exception
    */
   @Test
   public void testPartitionedRegion() throws Exception {
-    initManagement(false);
-
-    VM managingNode = getManagingNode();
-
-    VM[] managedNodes = new VM[getManagedNodeList().size()];
+    createMembersAndThenManagers_tmp();
 
-    getManagedNodeList().toArray(managedNodes);
-    // Adding notif listener for remote cache members
+    // Adding notification listener for remote cache memberVMs
+    addMemberNotificationListener(this.managerVM, 3); // TODO: why?
 
-    addMemberListener(managingNode);
-
-    for (int j = 0; j < managedNodes.length; j++) {
-
-      VM vm = managedNodes[j];
-      createPartitionRegion(vm, PARTITIONED_REGION_NAME);
-      validatePartitionRegionAfterCreate(vm);
+    for (VM memberVM : this.memberVMs) {
+      createPartitionRegion_tmp(memberVM, PARTITIONED_REGION_NAME);
+      verifyPartitionRegionAfterCreate(memberVM);
     }
 
+    verifyRemotePartitionRegion(this.managerVM);
 
-    validateRemotePartitionRegion(managingNode);
-
-    for (VM vm : getManagedNodeList()) {
-
-      closeRegion(vm, PARTITIONED_REGION_PATH);
-      validatePartitionRegionAfterClose(vm);
+    for (VM memberVM : this.memberVMs) {
+      closeRegion(memberVM, PARTITIONED_REGION_PATH);
+      verifyPartitionRegionAfterClose(memberVM);
     }
+
+    verifyMemberNotifications(this.managerVM, PARTITIONED_REGION_NAME, 3);
   }
 
   /**
    * Tests all Region MBean related Management APIs
-   * 
+   * <p>
    * a) Notification propagated to member MBean while a region is created
-   * 
+   * <p>
    * b) Creates and check a Fixed Partitioned Region
-   * 
-   * @throws Exception
    */
   @Test
   public void testFixedPRRegionMBean() throws Exception {
+    createMembersAndThenManagers_tmp();
 
-    initManagement(false);
-
-    VM managingNode = getManagingNode();
-
-    VM[] managedNodes = new VM[getManagedNodeList().size()];
-
-    getManagedNodeList().toArray(managedNodes);
-    // Adding notif listener for remote cache members
-    addMemberListener(managingNode);
-
-    for (int j = 0; j < managedNodes.length; j++) {
+    // Adding notification listener for remote cache memberVMs
+    addMemberNotificationListener(this.managerVM, 3); // TODO: why?
 
-      VM vm = managedNodes[j];
+    int primaryIndex = 0;
+    for (VM memberVM : this.memberVMs) {
+      List<FixedPartitionAttributes> fixedPartitionAttributesList =
+          createFixedPartitionList(primaryIndex + 1);
+      memberVM.invoke(() -> createFixedPartitionRegion(fixedPartitionAttributesList));
+      primaryIndex++;
+    }
 
-      createFixedPartitionList(j + 1);
-      Object[] args = new Object[1];
-      args[0] = fpaList;
-      vm.invoke(RegionManagementDUnitTest.class, "createFixedPartitionRegion", args);
+    // // TODO: Workaround for bug 46683. Reenable validation when bug is fixed.
+    verifyRemoteFixedPartitionRegion(this.managerVM);
 
+    for (VM memberVM : this.memberVMs) {
+      closeRegion(memberVM, FIXED_PR_PATH);
     }
-    // Workaround for bug 46683. Renable validation when bug is fixed.
-    validateRemoteFixedPartitionRegion(managingNode);
 
-    for (VM vm : getManagedNodeList()) {
-      closeFixedPartitionRegion(vm);
-    }
+    verifyMemberNotifications(this.managerVM, FIXED_PR_PATH, 3);
   }
 
   /**
    * Tests a Distributed Region at Managing Node side while region is created in a member node
    * asynchronously.
-   * 
-   * @throws Exception
    */
   @Test
   public void testRegionAggregate() throws Exception {
-    initManagement(true);
-
-    VM managingNode = getManagingNode();
-
-    VM[] managedNodes = new VM[getManagedNodeList().size()];
+    createManagersAndThenMembers_tmp();
 
-    getManagedNodeList().toArray(managedNodes);
-    // Adding notif listener for remote cache members
-    addDistrListener(managingNode);
-
-
-    for (int j = 0; j < managedNodes.length; j++) {
-
-      VM vm = managedNodes[j];
-
-      createDistributedRegion(vm, REGION_NAME);
+    // Adding notification listener for remote cache memberVMs
+    addSystemNotificationListener(this.managerVM); // TODO: why?
 
+    for (VM memberVM : this.memberVMs) {
+      createDistributedRegion_tmp(memberVM, REGION_NAME);
     }
 
+    verifyDistributedMBean(this.managerVM, 3);
+    createDistributedRegion_tmp(this.managerVM, REGION_NAME);
+    verifyDistributedMBean(this.managerVM, 4);
 
-    validateDistributedMBean(managingNode, 3);
-
-    createDistributedRegion(managingNode, REGION_NAME);
-    validateDistributedMBean(managingNode, 4);
-
-
-
-    for (int j = 0; j < managedNodes.length; j++) {
-
-      VM vm = managedNodes[j];
-
-      closeRegion(vm, REGION_PATH);
-
+    for (VM memberVM : this.memberVMs) {
+      closeRegion(memberVM, REGION_PATH);
     }
-    ensureProxyCleanup(managingNode);
-
-    validateDistributedMBean(managingNode, 1);
 
-    closeRegion(managingNode, REGION_PATH);
-    validateDistributedMBean(managingNode, 0);
+    verifyProxyCleanup(this.managerVM);
 
+    verifyDistributedMBean(this.managerVM, 1);
+    closeRegion(this.managerVM, REGION_PATH);
+    verifyDistributedMBean(this.managerVM, 0);
 
+    verifySystemNotifications(this.managerVM, REGION_NAME, 3);
   }
 
   @Test
   public void testNavigationAPIS() throws Exception {
-    initManagement(true);
-    for (VM vm : managedNodeList) {
-      createDistributedRegion(vm, REGION_NAME);
-      createPartitionRegion(vm, PARTITIONED_REGION_NAME);
-    }
-    createDistributedRegion(managingNode, REGION_NAME);
-    createPartitionRegion(managingNode, PARTITIONED_REGION_NAME);
-    List<String> memberIds = new ArrayList<String>();
+    createManagersAndThenMembers_tmp();
 
-    for (VM vm : managedNodeList) {
-      memberIds.add(getMemberId(vm));
+    for (VM memberVM : this.memberVMs) {
+      createDistributedRegion_tmp(memberVM, REGION_NAME);
+      createPartitionRegion_tmp(memberVM, PARTITIONED_REGION_NAME);
     }
-    checkNavigationAPIS(managingNode, memberIds);
-
 
+    createDistributedRegion_tmp(this.managerVM, REGION_NAME);
+    createPartitionRegion_tmp(this.managerVM, PARTITIONED_REGION_NAME);
+    List<String> memberIds = new ArrayList<>();
 
-    for (VM vm : managedNodeList) {
-      closeRegion(vm, REGION_PATH);
+    for (VM memberVM : this.memberVMs) {
+      memberIds.add(getDistributedMemberId_tmp(memberVM));
     }
 
-    closeRegion(managingNode, REGION_PATH);
+    verifyNavigationApis(this.managerVM, memberIds);
 
+    for (VM memberVM : this.memberVMs) {
+      closeRegion(memberVM, REGION_PATH);
+    }
+    closeRegion(this.managerVM, REGION_PATH);
   }
 
-
-
   @Test
   public void testSubRegions() throws Exception {
-    initManagement(false);
-    for (VM vm : managedNodeList) {
-      createLocalRegion(vm, LOCAL_REGION_NAME);
-      createSubRegion(vm, LOCAL_REGION_NAME, LOCAL_SUB_REGION_NAME);
-    }
+    createMembersAndThenManagers_tmp();
 
-    for (VM vm : managedNodeList) {
-      checkSubRegions(vm, LOCAL_SUB_REGION_PATH);
+    for (VM memberVM : this.memberVMs) {
+      createLocalRegion_tmp(memberVM, LOCAL_REGION_NAME);
+      createSubRegion_tmp(memberVM, LOCAL_REGION_NAME, LOCAL_SUB_REGION_NAME);
     }
 
-    for (VM vm : managedNodeList) {
-      closeRegion(vm, LOCAL_REGION_NAME);
-      checkNullRegions(vm, LOCAL_SUB_REGION_NAME);
+    for (VM memberVM : this.memberVMs) {
+      verifySubRegions(memberVM, LOCAL_SUB_REGION_PATH);
     }
 
+    for (VM memberVM : this.memberVMs) {
+      closeRegion(memberVM, LOCAL_REGION_NAME);
+      verifyNullRegions(memberVM, LOCAL_SUB_REGION_NAME);
+    }
   }
 
-
-
   @Test
   public void testSpecialRegions() throws Exception {
-    initManagement(false);
-    createSpecialRegion(managedNodeList.get(0));
-    DistributedMember member = getMember(managedNodeList.get(0));
-    checkSpecialRegion(managingNode, member);
-  }
-
-
-  public void createSpecialRegion(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableRunnable("Check Sub Regions") {
-
-        public void run() {
-          Cache cache = getCache();
-          AttributesFactory attributesFactory = new AttributesFactory();
-          attributesFactory.setValueConstraint(Portfolio.class);
-          RegionAttributes regionAttributes = attributesFactory.create();
-
-          cache.createRegion("p-os", regionAttributes);
-          cache.createRegion("p_os", regionAttributes);
-        }
-      });
-
-    }
-  }
-
-  public void checkSpecialRegion(VM vm1, final DistributedMember member) throws Exception {
-    {
-      vm1.invoke(new SerializableRunnable("Check Sub Regions") {
-
-        public void run() {
-
-          ManagementService service = getManagementService();
-
-          try {
-            MBeanUtil.getDistributedRegionMbean("/p-os", 1);
-            MBeanUtil.getDistributedRegionMbean("/p_os", 1);
-
-          } catch (Exception e) {
-            InternalDistributedSystem.getLoggerI18n()
-                .fine("Undesired Result , DistributedRegionMXBean Should not be null" + e);
-          }
-
-        }
-      });
-
-    }
-
+    createMembersAndThenManagers_tmp();
+    createSpecialRegion(this.memberVMs[0]);
+    verifySpecialRegion(this.managerVM);
   }
 
   @Test
   public void testLruStats() throws Exception {
-    initManagement(false);
-    for (VM vm : managedNodeList) {
-      createDiskRegion(vm);
-
+    createMembersAndThenManagers_tmp();
+    for (VM memberVM : this.memberVMs) {
+      createDiskRegion(memberVM);
     }
-    checkEntrySize(managingNode, 3);
+    verifyEntrySize(this.managerVM, 3);
   }
 
-  public void createDiskRegion(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableRunnable("Check Sub Regions") {
-
-        public void run() {
-          AttributesFactory factory = new AttributesFactory();
-          factory.setScope(Scope.LOCAL);
-          factory.setEvictionAttributes(EvictionAttributes.createLRUMemoryAttributes(20,
-              new TestObjectSizerImpl(), EvictionAction.LOCAL_DESTROY));
-          /*
-           * File d = new File("DiskRegions" + OSProcess.getId()); d.mkdirs();
-           * 
-           * DiskStoreFactory dsf = getCache().createDiskStoreFactory(); dsf.setDiskDirs(new
-           * File[]{d}); factory.setDiskSynchronous(true); DiskStore ds = dsf.create(REGION_NAME);
-           * factory.setDiskStoreName(ds.getName());
-           */
-          Region region = getCache().createRegion(REGION_NAME, factory.create());
-
-          LRUStatistics lruStats = getLRUStats(region);
-
-          assertNotNull(lruStats);
-
-          RegionMXBean bean = managementService.getLocalRegionMBean(REGION_PATH);
-
-          assertNotNull(bean);
-
-          int total;
-          for (total = 0; total < 10000; total++) {
-            int[] array = new int[250];
-            array[0] = total;
-            region.put(new Integer(total), array);
-          }
-          assertTrue(bean.getEntrySize() > 0);
-          LogWriterUtils.getLogWriter().info("DEBUG: EntrySize =" + bean.getEntrySize());
-
-
-
-        }
-      });
+  private void closeRegion(final VM anyVM, final String regionPath) {
+    anyVM.invoke("closeRegion", () -> getCache_tmp().getRegion(regionPath).close());
+  }
 
-    }
+  private void createSpecialRegion(final VM memberVM) throws Exception {
+    memberVM.invoke("createSpecialRegion", () -> {
+      AttributesFactory attributesFactory = new AttributesFactory();
+      attributesFactory.setValueConstraint(Portfolio.class);
+      RegionAttributes regionAttributes = attributesFactory.create();
 
+      Cache cache = getCache_tmp();
+      cache.createRegion("p-os", regionAttributes);
+      cache.createRegion("p_os", regionAttributes);
+    });
   }
 
-  public void checkEntrySize(VM vm1, final int expectedMembers) throws Exception {
-    {
-      vm1.invoke(new SerializableRunnable("Check Sub Regions") {
+  private void verifySpecialRegion(final VM managerVM) throws Exception {
+    managerVM.invoke("verifySpecialRegion", () -> {
+      awaitDistributedRegionMXBean("/p-os", 1); // TODO: why?
+      awaitDistributedRegionMXBean("/p_os", 1);
+    });
+  }
 
-        public void run() {
+  private void createDiskRegion(final VM memberVM) throws Exception {
+    memberVM.invoke("createDiskRegion", () -> {
+      AttributesFactory factory = new AttributesFactory();
+      factory.setScope(Scope.LOCAL);
+      factory.setEvictionAttributes(EvictionAttributes.createLRUMemoryAttributes(20,
+          new TestObjectSizerImpl(), EvictionAction.LOCAL_DESTROY));
 
-          DistributedRegionMXBean bean = null;
-          try {
-            bean = MBeanUtil.getDistributedRegionMbean(REGION_PATH, expectedMembers);
-          } catch (Exception e) {
-            InternalDistributedSystem.getLoggerI18n()
-                .fine("Undesired Result , DistributedRegionMXBean Should not be null" + e);
-          }
+      Region region = getCache_tmp().createRegion(REGION_NAME, factory.create());
 
-          assertNotNull(bean);
+      LRUStatistics lruStats =
+          ((AbstractRegion) region).getEvictionController().getLRUHelper().getStats();
+      assertThat(lruStats).isNotNull();
 
-          assertTrue(bean.getEntrySize() > 0);
-          LogWriterUtils.getLogWriter().info("DEBUG: EntrySize =" + bean.getEntrySize());
-        }
-      });
-
-    }
+      RegionMXBean regionMXBean = getManagementService_tmp().getLocalRegionMBean(REGION_PATH);
+      assertThat(regionMXBean).isNotNull();
 
+      int total;
+      for (total = 0; total < 10000; total++) { // TODO: why so many?
+        int[] array = new int[250];
+        array[0] = total;
+        region.put(new Integer(total), array);
+      }
+      assertThat(regionMXBean.getEntrySize()).isGreaterThan(0);
+    });
   }
 
-  protected LRUStatistics getLRUStats(Region region) {
-    final LocalRegion l = (LocalRegion) region;
-    return l.getEvictionController().getLRUHelper().getStats();
+  private void verifyEntrySize(final VM managerVM, final int expectedMembers) throws Exception {
+    managerVM.invoke("verifyEntrySize", () -> {
+      DistributedRegionMXBean distributedRegionMXBean =
+          awaitDistributedRegionMXBean(REGION_PATH, expectedMembers);
+      assertThat(distributedRegionMXBean).isNotNull();
+      assertThat(distributedRegionMXBean.getEntrySize()).isGreaterThan(0);
+    });
   }
 
-  @SuppressWarnings("serial")
-  public void checkSubRegions(VM vm1, final String subRegionPath) throws Exception {
-    {
-      vm1.invoke(new SerializableRunnable("Check Sub Regions") {
-
-        public void run() {
-
-          RegionMXBean bean = managementService.getLocalRegionMBean(subRegionPath);
-          assertNotNull(bean);
-
-        }
-      });
-
-    }
+  private void verifySubRegions(final VM memberVM, final String subRegionPath) throws Exception {
+    memberVM.invoke("verifySubRegions", () -> {
+      RegionMXBean regionMXBean = getManagementService_tmp().getLocalRegionMBean(subRegionPath);
+      assertThat(regionMXBean).isNotNull();
+    });
   }
 
-  @SuppressWarnings("serial")
-  public void checkNullRegions(VM vm1, final String subRegionPath) throws Exception {
-    {
-      vm1.invoke(new SerializableRunnable("Check Sub Regions") {
-
-        public void run() {
+  private void verifyNullRegions(final VM memberVM, final String subRegionPath) throws Exception {
+    memberVM.invoke("verifyNullRegions", () -> {
+      RegionMXBean regionMXBean = getManagementService_tmp().getLocalRegionMBean(subRegionPath);
+      assertThat(regionMXBean).isNull();
+    });
+  }
 
-          RegionMXBean bean = managementService.getLocalRegionMBean(subRegionPath);
-          assertNull(bean);
+  private void verifyNavigationApis(final VM managerVM, final List<String> memberIds) {
+    managerVM.invoke("verifyNavigationApis", () -> {
+      ManagementService service = getManagementService_tmp();
+      assertThat(service.getDistributedSystemMXBean()).isNotNull();
 
-        }
-      });
+      awaitMemberCount(4);
 
-    }
-  }
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+      assertThat(distributedSystemMXBean.listDistributedRegionObjectNames()).hasSize(2);
 
+      assertThat(distributedSystemMXBean.fetchDistributedRegionObjectName(PARTITIONED_REGION_PATH))
+          .isNotNull();
+      assertThat(distributedSystemMXBean.fetchDistributedRegionObjectName(REGION_PATH)).isNotNull();
 
+      ObjectName actualName =
+          distributedSystemMXBean.fetchDistributedRegionObjectName(PARTITIONED_REGION_PATH);
+      ObjectName expectedName =
+          MBeanJMXAdapter.getDistributedRegionMbeanName(PARTITIONED_REGION_PATH);
+      assertThat(actualName).isEqualTo(expectedName);
 
-  protected void checkNavigationAPIS(final VM vm, final List<String> managedNodeMemberIds) {
-    SerializableRunnable checkNavigationAPIS = new SerializableRunnable("checkNavigationAPIS") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        ManagementService service = getManagementService();
-        final DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
+      actualName = distributedSystemMXBean.fetchDistributedRegionObjectName(REGION_PATH);
+      expectedName = MBeanJMXAdapter.getDistributedRegionMbeanName(REGION_PATH);
+      assertThat(actualName).isEqualTo(expectedName);
 
-        assertNotNull(service.getDistributedSystemMXBean());
+      for (String memberId : memberIds) {
+        ObjectName objectName = MBeanJMXAdapter.getMemberMBeanName(memberId);
+        awaitMemberMXBeanProxy(objectName);
 
-        waitForAllMembers(4);
-        assertTrue(bean.listDistributedRegionObjectNames().length == 2);
-        try {
-          assertNotNull(bean.fetchDistributedRegionObjectName(PARTITIONED_REGION_PATH));
-          assertNotNull(bean.fetchDistributedRegionObjectName(REGION_PATH));
-          ObjectName actualName = bean.fetchDistributedRegionObjectName(PARTITIONED_REGION_PATH);
-          ObjectName expectedName =
-              MBeanJMXAdapter.getDistributedRegionMbeanName(PARTITIONED_REGION_PATH);
-          assertEquals(expectedName, actualName);
+        ObjectName[] objectNames = distributedSystemMXBean.fetchRegionObjectNames(objectName);
+        assertThat(objectNames).isNotNull();
+        assertThat(objectNames).hasSize(2);
 
-          actualName = bean.fetchDistributedRegionObjectName(REGION_PATH);
-          expectedName = MBeanJMXAdapter.getDistributedRegionMbeanName(REGION_PATH);
-          assertEquals(expectedName, actualName);
+        List<ObjectName> listOfNames = Arrays.asList(objectNames);
 
-        } catch (Exception e) {
-          fail("fetchDistributedRegionObjectName () Unsuccessful " + e);
-        }
+        expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId, PARTITIONED_REGION_PATH);
+        assertThat(listOfNames).contains(expectedName);
 
-        for (String memberId : managedNodeMemberIds) {
-          ObjectName memberMBeanName = MBeanJMXAdapter.getMemberMBeanName(memberId);
-          ObjectName expectedName;
-          try {
-            waitForProxy(memberMBeanName, MemberMXBean.class);
-
-            ObjectName[] regionMBeanNames = bean.fetchRegionObjectNames(memberMBeanName);
-            assertNotNull(regionMBeanNames);
-            assertTrue(regionMBeanNames.length == 2);
-            List<ObjectName> listOfNames = Arrays.asList(regionMBeanNames);
-
-            expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId, PARTITIONED_REGION_PATH);
-            listOfNames.contains(expectedName);
-            expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId, REGION_PATH);
-            listOfNames.contains(expectedName);
-          } catch (Exception e) {
-            fail("fetchRegionObjectNames () Unsuccessful " + e);
-          }
-        }
+        expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId, REGION_PATH);
+        assertThat(listOfNames).contains(expectedName);
+      }
 
-        for (String memberId : managedNodeMemberIds) {
-          ObjectName expectedName;
-          ObjectName actualName;
-          ObjectName memberMBeanName = MBeanJMXAdapter.getMemberMBeanName(memberId);
-          try {
-            waitForProxy(memberMBeanName, MemberMXBean.class);
-            expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId, PARTITIONED_REGION_PATH);
-            waitForProxy(expectedName, RegionMXBean.class);
-            actualName = bean.fetchRegionObjectName(memberId, PARTITIONED_REGION_PATH);
-
-            assertEquals(expectedName, actualName);
-            expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId, REGION_PATH);
-            waitForProxy(expectedName, RegionMXBean.class);
-            actualName = bean.fetchRegionObjectName(memberId, REGION_PATH);
-
-            assertEquals(expectedName, actualName);
-          } catch (Exception e) {
-            fail("fetchRegionObjectName () Unsuccessful ");
-          }
-        }
+      for (String memberId : memberIds) {
+        ObjectName objectName = MBeanJMXAdapter.getMemberMBeanName(memberId);
+        awaitMemberMXBeanProxy(objectName);
 
-      }
-    };
-    vm.invoke(checkNavigationAPIS);
-  }
+        expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId, PARTITIONED_REGION_PATH);
+        awaitRegionMXBeanProxy(expectedName);
 
+        actualName =
+            distributedSystemMXBean.fetchRegionObjectName(memberId, PARTITIONED_REGION_PATH);
+        assertThat(actualName).isEqualTo(expectedName);
 
-  protected void putBulkData(final VM vm, final int numKeys) {
-    SerializableRunnable putBulkData = new SerializableRunnable("putBulkData") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Region region = cache.getRegion(REGION_PATH);
-        for (int i = 0; i < numKeys; i++) {
-          region.put(i, i * i);
-        }
+        expectedName = MBeanJMXAdapter.getRegionMBeanName(memberId, REGION_PATH);
+        awaitRegionMXBeanProxy(expectedName);
 
+        actualName = distributedSystemMXBean.fetchRegionObjectName(memberId, REGION_PATH);
+        assertThat(actualName).isEqualTo(expectedName);
       }
-    };
-    vm.invoke(putBulkData);
+    });
   }
 
-
-
   /**
-   * creates a Fixed Partition List to be used for Fixed Partition Region
-   * 
-   * @param primaryIndex index for each fixed partition
+   * Invoked in controller VM
    */
-  private static void createFixedPartitionList(int primaryIndex) {
-    fpaList.clear();
+  private List<FixedPartitionAttributes> createFixedPartitionList(final int primaryIndex) {
+    List<FixedPartitionAttributes> fixedPartitionAttributesList = new ArrayList<>();
     if (primaryIndex == 1) {
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q1", true, 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q2", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q3", 3));
+      fixedPartitionAttributesList
+          .add(FixedPartitionAttributes.createFixedPartition("Q1", true, 3));
+      fixedPartitionAttributesList.add(FixedPartitionAttributes.createFixedPartition("Q2", 3));
+      fixedPartitionAttributesList.add(FixedPartitionAttributes.createFixedPartition("Q3", 3));
     }
     if (primaryIndex == 2) {
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q1", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q2", true, 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q3", 3));
+      fixedPartitionAttributesList.add(FixedPartitionAttributes.createFixedPartition("Q1", 3));
+      fixedPartitionAttributesList
+          .add(FixedPartitionAttributes.createFixedPartition("Q2", true, 3));
+      fixedPartitionAttributesList.add(FixedPartitionAttributes.createFixedPartition("Q3", 3));
     }
     if (primaryIndex == 3) {
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q1", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q2", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q3", true, 3));
+      fixedPartitionAttributesList.add(FixedPartitionAttributes.createFixedPartition("Q1", 3));
+      fixedPartitionAttributesList.add(FixedPartitionAttributes.createFixedPartition("Q2", 3));
+      fixedPartitionAttributesList
+          .add(FixedPartitionAttributes.createFixedPartition("Q3", true, 3));
     }
-
+    return fixedPartitionAttributesList;
   }
 
-
-
   /**
-   * Creates a Fixed Partitioned Region
-   * 
-   * @param fpaList partition list
+   * Invoked in member VMs
    */
-  protected static void createFixedPartitionRegion(List<FixedPartitionAttributes> fpaList) {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    SystemManagementService service = (SystemManagementService) getManagementService();
+  private void createFixedPartitionRegion(
+      final List<FixedPartitionAttributes> fixedPartitionAttributesList) {
+    SystemManagementService service = getSystemManagementService_tmp();
 
-    PartitionAttributesFactory paf = new PartitionAttributesFactory();
+    PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory();
 
-    paf.setRedundantCopies(2).setTotalNumBuckets(12);
-    for (FixedPartitionAttributes fpa : fpaList) {
-      paf.addFixedPartitionAttributes(fpa);
+    partitionAttributesFactory.setRedundantCopies(2).setTotalNumBuckets(12);
+    for (FixedPartitionAttributes fixedPartitionAttributes : fixedPartitionAttributesList) {
+      partitionAttributesFactory.addFixedPartitionAttributes(fixedPartitionAttributes);
     }
-    paf.setPartitionResolver(new SingleHopQuarterPartitionResolver());
-
-    AttributesFactory attr = new AttributesFactory();
-    attr.setPartitionAttributes(paf.create());
-    fixedPrRegion = cache.createRegion(FIXED_PR_NAME, attr.create());
-    assertNotNull(fixedPrRegion);
-    LogWriterUtils.getLogWriter().info("Partitioned Region " + FIXED_PR_NAME
-        + " created Successfully :" + fixedPrRegion.toString());
-
-    RegionMXBean bean = service.getLocalRegionMBean(FIXED_PR_PATH);
-    RegionAttributes regAttrs = fixedPrRegion.getAttributes();
-
-    LogWriterUtils.getLogWriter().info("FixedPartitionAttribute From GemFire :"
-        + regAttrs.getPartitionAttributes().getFixedPartitionAttributes());
+    partitionAttributesFactory.setPartitionResolver(new SingleHopQuarterPartitionResolver());
 
-    RegionAttributesData data = bean.listRegionAttributes();
+    AttributesFactory attributesFactory = new AttributesFactory();
+    attributesFactory.setPartitionAttributes(partitionAttributesFactory.create());
 
-    PartitionAttributesData parData = bean.listPartitionAttributes();
+    fixedPartitionedRegion = getCache_tmp().createRegion(FIXED_PR_NAME, attributesFactory.create());
+    assertThat(fixedPartitionedRegion).isNotNull();
 
-    assertPartitionData(regAttrs, parData);
+    RegionMXBean regionMXBean = service.getLocalRegionMBean(FIXED_PR_PATH);
+    RegionAttributes regionAttributes = fixedPartitionedRegion.getAttributes();
 
-    FixedPartitionAttributesData[] fixedPrData = bean.listFixedPartitionAttributes();
+    PartitionAttributesData partitionAttributesData = regionMXBean.listPartitionAttributes();
+    verifyPartitionData(regionAttributes, partitionAttributesData);
 
-    assertNotNull(fixedPrData);
+    FixedPartitionAttributesData[] fixedPartitionAttributesData =
+        regionMXBean.listFixedPartitionAttributes();
+    assertThat(fixedPartitionAttributesData).isNotNull();
+    assertThat(fixedPartitionAttributesData).hasSize(3);
 
-    assertEquals(3, fixedPrData.length);
-    for (int i = 0; i < fixedPrData.length; i++) {
-      LogWriterUtils.getLogWriter()
-          .info("<ExpectedString> Fixed PR Data is " + fixedPrData[i] + "</ExpectedString> ");
+    for (int i = 0; i < fixedPartitionAttributesData.length; i++) {
+      // LogWriterUtils.getLogWriter().info("<ExpectedString> Fixed PR Data is " +
+      // fixedPartitionAttributesData[i] + "</ExpectedString> ");
     }
   }
 
-  /**
-   * Verifies the Fixed Partition Region for partition related attributes
-   * 
-   * @param vm
-   */
-  protected void validateRemoteFixedPartitionRegion(final VM vm) throws Exception {
-    SerializableRunnable verifyFixedRegion = new SerializableRunnable("Verify Partition region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Set<DistributedMember> otherMemberSet =
-            cache.getDistributionManager().getOtherNormalDistributionManagerIds();
-
-        for (DistributedMember member : otherMemberSet) {
-          RegionMXBean bean = null;
-          try {
-            bean = MBeanUtil.getRegionMbeanProxy(member, FIXED_PR_PATH);
-          } catch (Exception e) {
-            InternalDistributedSystem.getLoggerI18n()
-                .fine("Undesired Result , RegionMBean Should not be null");
-          }
-          PartitionAttributesData data = bean.listPartitionAttributes();
-          assertNotNull(data);
-          FixedPartitionAttributesData[] fixedPrData = bean.listFixedPartitionAttributes();
-          assertNotNull(fixedPrData);
-          assertEquals(3, fixedPrData.length);
-          for (int i = 0; i < fixedPrData.length; i++) {
-            LogWriterUtils.getLogWriter().info(
-                "<ExpectedString> Remote PR Data is " + fixedPrData[i] + "</ExpectedString> ");
-          }
-        }
-
+  // /**
+  // * Invoked in manager VM
+  // */
+  // private void verifyRemoteFixedPartitionRegion(final VM vm) throws Exception {
+  // vm.invoke("Verify Partition region", () -> {
+  // Set<DistributedMember> otherMemberSet =
+  // getDistributionManager_tmp().getOtherNormalDistributionManagerIds();
+  //
+  // for (DistributedMember member : otherMemberSet) {
+  // RegionMXBean regionMXBean = awaitRegionMXBeanProxy(member, FIXED_PR_PATH);
+  //
+  // PartitionAttributesData partitionAttributesData = regionMXBean.listPartitionAttributes();
+  // assertNotNull(partitionAttributesData);
+  //
+  // FixedPartitionAttributesData[] fixedPartitionAttributesData =
+  // regionMXBean.listFixedPartitionAttributes();
+  // assertNotNull(fixedPartitionAttributesData);
+  // assertEquals(3, fixedPartitionAttributesData.length);
+  //
+  // for (int i = 0; i < fixedPartitionAttributesData.length; i++) {
+  // //LogWriterUtils.getLogWriter().info("<ExpectedString> Remote PR Data is " +
+  // fixedPartitionAttributesData[i] + "</ExpectedString> ");
+  // }
+  // }
+  // });
+  // }
+
+  private void addMemberNotificationListener(final VM managerVM, final int expectedMembers) {
+    managerVM.invoke("addMemberNotificationListener", () -> {
+      Set<DistributedMember> otherMemberSet = getOtherNormalMembers_tmp();
+      assertThat(otherMemberSet).hasSize(expectedMembers);
+
+      SystemManagementService service = getSystemManagementService_tmp();
+
+      List<Notification> notifications = new ArrayList<>();
+      MEMBER_NOTIFICATIONS_REF.set(notifications);
+
+      for (DistributedMember member : otherMemberSet) {
+        MemberNotificationListener listener = new MemberNotificationListener(notifications);
+        ObjectName objectName = service.getMemberMBeanName(member);
+        awaitMemberMXBeanProxy(objectName);
+
+        ManagementFactory.getPlatformMBeanServer().addNotificationListener(objectName, listener,
+            null, null);
       }
-
-    };
-    vm.invoke(verifyFixedRegion);
-  }
-
-  /**
-   * Add a Notification listener to MemberMBean
-   * 
-   * @param vm
-   */
-  protected void addMemberListener(final VM vm) {
-    SerializableRunnable addMemberListener = new SerializableRunnable("addMemberListener") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-
-        SystemManagementService service = (SystemManagementService) getManagementService();
-
-        Set<DistributedMember> otherMemberSet =
-            cache.getDistributionManager().getOtherNormalDistributionManagerIds();
-
-        for (DistributedMember member : otherMemberSet) {
-
-          MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
-
-          RegionNotif regionCreate = new RegionNotif();
-
-          ObjectName memberMBeanName;
-          try {
-            memberMBeanName = service.getMemberMBeanName(member);
-            Set<ObjectName> names = service.queryMBeanNames(member);
-            if (names != null) {
-              for (ObjectName name : names) {
-                LogWriterUtils.getLogWriter()
-                    .info("<ExpectedString> ObjectNames arr" + name + "</ExpectedString> ");
-              }
-            }
-            waitForProxy(memberMBeanName, MemberMXBean.class);
-            mbeanServer.addNotificationListener(memberMBeanName, regionCreate, null, null);
-          } catch (NullPointerException e) {
-            Assert.fail("FAILED WITH EXCEPION", e);
-          } catch (InstanceNotFoundException e) {
-            Assert.fail("FAILED WITH EXCEPION", e);
-          } catch (Exception e) {
-            Assert.fail("FAILED WITH EXCEPION", e);
-          }
-
-        }
-
-      }
-    };
-    vm.invoke(addMemberListener);
-
+    });
   }
 
   /**
    * Add a Notification listener to DistributedSystemMBean which should gather all the notifications
    * which are propagated through all individual MemberMBeans Hence Region created/destroyed should
    * be visible to this listener
-   * 
-   * @param vm
    */
-  protected void addDistrListener(final VM vm) {
-    SerializableRunnable addDistrListener = new SerializableRunnable("addDistrListener") {
-      public void run() {
-        MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
-
-        DistrNotif regionCreate = new DistrNotif();
-
-        ObjectName systemMBeanName;
-        try {
-          systemMBeanName = MBeanJMXAdapter.getDistributedSystemName();
-          mbeanServer.addNotificationListener(systemMBeanName, regionCreate, null, null);
-
-        } catch (NullPointerException e) {
-          Assert.fail("FAILED WITH EXCEPION", e);
-        } catch (InstanceNotFoundException e) {
-          Assert.fail("FAILED WITH EXCEPION", e);
+  private void addSystemNotificationListener(final VM managerVM) {
+    managerVM.invoke("addSystemNotificationListener", () -> {
+      awaitDistributedSystemMXBean();
+
+      List<Notification> notifications = new ArrayList<>();
+      SYSTEM_NOTIFICATIONS_REF.set(notifications);
+
+      DistributedSystemNotificationListener listener =
+          new DistributedSystemNotificationListener(notifications);
+      ObjectName objectName = MBeanJMXAdapter.getDistributedSystemName();
+      ManagementFactory.getPlatformMBeanServer().addNotificationListener(objectName, listener, null,
+          null);
+    });
+  }
 
+  private void verifyMemberNotifications(final VM managerVM, final String regionName,
+      final int expectedMembers) {
+    managerVM.invoke("verifyMemberNotifications", () -> {
+      assertThat(MEMBER_NOTIFICATIONS_REF.get()).isNotNull();
+      assertThat(MEMBER_NOTIFICATIONS_REF.get()).hasSize(expectedMembers * 2);
+
+      int regionCreatedCount = 0;
+      int regionDestroyedCount = 0;
+      for (Notification notification : MEMBER_NOTIFICATIONS_REF.get()) {
+        if (JMXNotificationType.REGION_CREATED.equals(notification.getType())) {
+          regionCreatedCount++;
+          assertThat(notification.getMessage()).contains(regionName);
+        } else if (JMXNotificationType.REGION_CLOSED.equals(notification.getType())) {
+          regionDestroyedCount++;
+          assertThat(notification.getMessage()).contains(regionName);
+        } else {
+          fail("Unexpected notification type: " + notification.getType());
         }
-
       }
-    };
-    vm.invoke(addDistrListener);
 
+      assertThat(regionCreatedCount).isEqualTo(expectedMembers);
+      assertThat(regionDestroyedCount).isEqualTo(expectedMembers);
+    });
   }
 
-  public void ensureProxyCleanup(final VM vm) {
-
-    SerializableRunnable ensureProxyCleanup = new SerializableRunnable("Ensure Proxy cleanup") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Set<DistributedMember> otherMemberSet =
-            cache.getDistributionManager().getOtherNormalDistributionManagerIds();
-
-        final SystemManagementService service = (SystemManagementService) getManagementService();
-
-        for (final DistributedMember member : otherMemberSet) {
-          RegionMXBean bean = null;
-          try {
-
-            Wait.waitForCriterion(new WaitCriterion() {
-
-              RegionMXBean bean = null;
-
-              public String description() {
-                return "Waiting for the proxy to get deleted at managing node";
-              }
-
-              public boolean done() {
-                ObjectName objectName = service.getRegionMBeanName(member, REGION_PATH);
-                bean = service.getMBeanProxy(objectName, RegionMXBean.class);
-                boolean done = (bean == null);
-                return done;
-              }
-
-            }, MAX_WAIT, 500, true);
-
-          } catch (Exception e) {
-            fail("could not remove proxies in required time");
-
-          }
-          assertNull(bean);
-
+  // <[javax.management.Notification[source=10.118.33.232(17632)<v1>-32770][type=gemfire.distributedsystem.cache.region.created][message=Region
+  // Created With Name /MANAGEMENT_TEST_REGION],
+  // javax.management.Notification[source=10.118.33.232(17633)<v2>-32771][type=gemfire.distributedsystem.cache.region.created][message=Region
+  // Created With Name /MANAGEMENT_TEST_REGION],
+  // javax.management.Notification[source=10.118.33.232(17634)<v3>-32772][type=gemfire.distributedsystem.cache.region.created][message=Region
+  // Created With Name /MANAGEMENT_TEST_REGION],
+  // javax.management.Notification[source=10.118.33.232(17632)<v1>-32770][type=gemfire.distributedsystem.cache.region.closed][message=Region
+  // Destroyed/Closed With Name /MANAGEMENT_TEST_REGION],
+  // javax.management.Notification[source=10.118.33.232(17633)<v2>-32771][type=gemfire.distributedsystem.cache.region.closed][message=Region
+  // Destroyed/Closed With Name /MANAGEMENT_TEST_REGION],
+  // javax.management.Notification[source=10.118.33.232(17634)<v3>-32772][type=gemfire.distributedsystem.cache.region.closed][message=Region
+  // Destroyed/Closed With Name /MANAGEMENT_TEST_REGION]]>
+
+  private void verifySystemNotifications(final VM managerVM, final String regionName,
+      final int expectedMembers) {
+    managerVM.invoke("verifySystemNotifications", () -> {
+      assertThat(SYSTEM_NOTIFICATIONS_REF.get()).isNotNull();
+      assertThat(SYSTEM_NOTIFICATIONS_REF.get()).hasSize(expectedMembers + 2); // 2 for the manager
+
+
+      int regionCreatedCount = 0;
+      int regionDestroyedCount = 0;
+      for (Notification notification : SYSTEM_NOTIFICATIONS_REF.get()) {
+        if (JMXNotificationType.REGION_CREATED.equals(notification.getType())) {
+          regionCreatedCount++;
+          assertThat(notification.getMessage()).contains(regionName);
+        } else if (JMXNotificationType.REGION_CLOSED.equals(notification.getType())) {
+          regionDestroyedCount++;
+          assertThat(notification.getMessage()).contains(regionName);
+        } else {
+          fail("Unexpected notification type: " + notification.getType());
         }
-
       }
-    };
-    vm.invoke(ensureProxyCleanup);
-  }
-
-  /**
-   * Verifies a Remote Distributed Region
-   * 
-   * @param vm
-   */
-  protected void verifyRemoteDistributedRegion(final VM vm, final int expectedMembers)
-      throws Exception {
-    SerializableRunnable verifyRegion = new SerializableRunnable("Verify Distributed region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Set<DistributedMember> otherMemberSet =
-            cache.getDistributionManager().getOtherNormalDistributionManagerIds();
-
-        for (DistributedMember member : otherMemberSet) {
-          RegionMXBean bean = null;
-          try {
-            bean = MBeanUtil.getRegionMbeanProxy(member, REGION_PATH);
-          } catch (Exception e) {
-            InternalDistributedSystem.getLoggerI18n()
-                .fine("Undesired Result , RegionMBean Should not be null" + e);
-
-          }
-          assertNotNull(bean);
-
-          RegionAttributesData data = bean.listRegionAttributes();
-          assertNotNull(data);
-          MembershipAttributesData membershipData = bean.listMembershipAttributes();
-          EvictionAttributesData evictionData = bean.listEvictionAttributes();
-          assertNotNull(membershipData);
-          assertNotNull(evictionData);
-          LogWriterUtils.getLogWriter().info("<ExpectedString> Membership Data is "
-              + membershipData.toString() + "</ExpectedString> ");
-          LogWriterUtils.getLogWriter().info("<ExpectedString> Eviction Data is "
-              + membershipData.toString() + "</ExpectedString> ");
-
-        }
-        DistributedRegionMXBean bean = null;
-        try {
-          bean = MBeanUtil.getDistributedRegionMbean(REGION_PATH, expectedMembers);
-        } catch (Exception e) {
-          InternalDistributedSystem.getLoggerI18n()
-              .fine("Undesired Result , DistributedRegionMXBean Should not be null" + e);
-        }
-
-        assertNotNull(bean);
-        assertEquals(REGION_PATH, bean.getFullPath());
 
+      assertThat(regionCreatedCount).isEqualTo(1); // just the manager
+      assertThat(regionDestroyedCount).isEqualTo(expectedMembers + 1); // all 3 members + manager
+    });
+  }
 
+  // <[javax.management.Notification[source=192.168.1.72(18496)<v27>-32770][type=gemfire.distributedsystem.cache.region.created][message=Region
+  // Created With Name /MANAGEMENT_TEST_REGION],
+  // javax.management.Notification[source=192.168.1.72(18497)<v28>-32771][type=gemfire.distributedsystem.cache.region.closed][message=Region
+  // Destroyed/Closed With Name /MANAGEMENT_TEST_REGION],
+  // javax.management.Notification[source=192.168.1.72(18498)<v29>-32772][type=gemfire.distributedsystem.cache.region.closed][message=Region
+  // Destroyed/Closed With Name /MANAGEMENT_TEST_REGION],
+  // javax.management.Notification[source=192.168.1.72(18499)<v30>-32773][type=gemfire.distributedsystem.cache.region.closed][message=Region
+  // Destroyed/Closed With Name /MANAGEMENT_TEST_REGION],
+  // javax.management.Notification[source=192.168.1.72(18496)<v27>-32770][type=gemfire.distributedsystem.cache.region.closed][message=Region
+  // Destroyed/Closed With Name /MANAGEMENT_TEST_REGION]]>
+
+  private void verifyProxyCleanup(final VM managerVM) {
+    managerVM.invoke("verifyProxyCleanup", () -> {
+      SystemManagementService service = getSystemManagementService_tmp();
+
+      Set<DistributedMember> otherMemberSet = getOtherNormalMembers_tmp();
+      for (final DistributedMember member : otherMemberSet) {
+        String alias = "Waiting for the proxy to get deleted at managing node";
+        await(alias).until(
+            () -> assertThat(service.getMBeanProxy(service.getRegionMBeanName(member, REGION_PATH),
+                RegionMXBean.class)).isNull());
       }
-    };
-    vm.invoke(verifyRegion);
+    });
   }
 
+  private void verifyRemoteDistributedRegion(final VM managerVM, final int expectedMembers)
+      throws Exception {
+    managerVM.invoke("verifyRemoteDistributedRegion", () -> {
+      Set<DistributedMember> otherMemberSet = getOtherNormalMembers_tmp();
+      assertThat(otherMemberSet).hasSize(expectedMembers);
 
-  protected void validateDistributedMBean(final VM vm, final int expectedMembers) {
-    SerializableRunnable verifyRegion = new SerializableRunnable("Verify Distributed region") {
-      public void run() {
-        DistributedRegionMXBean bean = null;
-        DistributedSystemMXBean sysMBean = null;
-        final ManagementService service = getManagementService();
-
-        if (expectedMembers == 0) {
-          try {
-            Wait.waitForCriterion(new WaitCriterion() {
-
-              RegionMXBean bean = null;
-
-              public String description() {
-                return "Waiting for the proxy to get deleted at managing node";
-              }
-
-              public boolean done() {
-                DistributedRegionMXBean bean = service.getDistributedRegionMXBean(REGION_PATH);
-                boolean done = (bean == null);
-                return done;
-              }
+      for (DistributedMember member : otherMemberSet) {
+        RegionMXBean regionMXBean = awaitRegionMXBeanProxy(member, REGION_PATH);
 
-            }, MAX_WAIT, 500, true);
+        RegionAttributesData regionAttributesData = regionMXBean.listRegionAttributes();
+        assertThat(regionAttributesData).isNotNull();
 
-          } catch (Exception e) {
-            fail("could not remove Aggregate Bean in required time");
+        MembershipAttributesData membershipAttributesData = regionMXBean.listMembershipAttributes();
+        assertThat(membershipAttributesData).isNotNull();
 
-          }
-          return;
-        }
-
-        try {
-          bean = MBeanUtil.getDistributedRegionMbean(REGION_PATH, expectedMembers);
-          sysMBean = service.getDistributedSystemMXBean();
-        } catch (Exception e) {
-          InternalDistributedSystem.getLoggerI18n()
-              .fine("Undesired Result , DistributedRegionMXBean Should not be null" + e);
-        }
+        EvictionAttributesData evictionAttributesData = regionMXBean.listEvictionAttributes();
+        assertThat(evictionAttributesData).isNotNull();
+      }
 
-        assertNotNull(bean);
-        assertEquals(REGION_PATH, bean.getFullPath());
-        assertEquals(expectedMembers, bean.getMemberCount());
-        assertEquals(expectedMembers, bean.getMembers().length);
+      DistributedRegionMXBean distributedRegionMXBean =
+          awaitDistributedRegionMXBean(REGION_PATH, expectedMembers);
 
-        // Check Stats related Data
-        // Add Mock testing
-        LogWriterUtils.getLogWriter().info("<ExpectedString> CacheListenerCallsAvgLatency is "
-            + bean.getCacheListenerCallsAvgLatency() + "</ExpectedString> ");
-        LogWriterUtils.getLogWriter().info("<ExpectedString> CacheWriterCallsAvgLatency is "
-            + bean.getCacheWriterCallsAvgLatency() + "</ExpectedString> ");
-        LogWriterUtils.getLogWriter().info(
-            "<ExpectedString> CreatesRate is " + bean.getCreatesRate() + "</ExpectedString> ");
+      assertThat(distributedRegionMXBean).isNotNull();
+      assertThat(distributedRegionMXBean.getFullPath()).isEqualTo(REGION_PATH);
+    });
+  }
 
+  private void verifyDistributedMBean(final VM managerVM, final int expectedMembers) {
+    managerVM.invoke("verifyDistributedMBean", () -> {
+      if (expectedMembers == 0) {
+        ManagementService service = getManagementService_tmp();
+        String alias = "Waiting for the proxy to get deleted at managing node";
+        await(alias)
+            .until(() -> assertThat(service.getDistributedRegionMXBean(REGION_PATH)).isNull());
+        return;
       }
-    };
-    // Test DistributedRegionMXBean
 
-    vm.invoke(verifyRegion);
+      DistributedRegionMXBean distributedRegionMXBean =
+          awaitDistributedRegionMXBean(REGION_PATH, expectedMembers);
+
+      assertThat(distributedRegionMXBean.getFullPath()).isEqualTo(REGION_PATH);
+      assertThat(distributedRegionMXBean.getMemberCount()).isEqualTo(expectedMembers);
+      assertThat(distributedRegionMXBean.getMembers()).hasSize(expectedMembers);
+
+      // Check Stats related Data
+      // LogWriterUtils.getLogWriter().info("<ExpectedString> CacheListenerCallsAvgLatency is " +
+      // distributedRegionMXBean.getCacheListenerCallsAvgLatency() + "</ExpectedString> ");
+      // LogWriterUtils.getLogWriter().info("<ExpectedString> CacheWriterCallsAvgLatency is " +
+      // distributedRegionMXBean.getCacheWriterCallsAvgLatency() + "</ExpectedString> ");
+      // LogWriterUtils.getLogWriter().info("<ExpectedString> CreatesRate is " +
+      // distributedRegionMXBean.getCreatesRate() + "</ExpectedString> ");
+    });
   }
 
-  /**
-   * Verifies a Remote Partition Region
-   * 
-   * @param vm
-   */
-  protected void validateRemotePartitionRegion(final VM vm) throws Exception {
-    SerializableRunnable verifyRegion = new SerializableRunnable("Verify Partition region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Set<DistributedMember> otherMemberSet =
-            cache.getDistributionManager().getOtherNormalDistributionManagerIds();
-
-        for (DistributedMember member : otherMemberSet) {
-          RegionMXBean bean = null;
-          try {
-            bean = MBeanUtil.getRegionMbeanProxy(member, PARTITIONED_REGION_PATH);
-          } catch (Exception e) {
-            InternalDistributedSystem.getLoggerI18n()
-                .fine("Undesired Result , RegionMBean Should not be null");
-          }
-          PartitionAttributesData data = bean.listPartitionAttributes();
-          assertNotNull(data);
-        }
-
-        ManagementService service = getManagementService();
-        DistributedRegionMXBean bean = service.getDistributedRegionMXBean(PARTITIONED_REGION_PATH);
-        assertEquals(3, bean.getMembers().length);
+  private void verifyRemotePartitionRegion(final VM managerVM) throws Exception {
+    managerVM.invoke("verifyRemotePartitionRegion", () -> {
+      Set<DistributedMember> otherMemberSet = getOtherNormalMembers_tmp();
 
+      for (DistributedMember member : otherMemberSet) {
+        RegionMXBean regionMXBean = awaitRegionMXBeanProxy(member, PARTITIONED_REGION_PATH);
+        PartitionAttributesData partitionAttributesData = regionMXBean.listPartitionAttributes();
+        assertThat(partitionAttributesData).isNotNull();
       }
 
-    };
-    vm.invoke(verifyRegion);
+      ManagementService service = getManagementService_tmp();
+      DistributedRegionMXBean distributedRegionMXBean =
+          service.getDistributedRegionMXBean(PARTITIONED_REGION_PATH);
+      assertThat(distributedRegionMXBean.getMembers()).hasSize(3);
+    });
   }
 
+  private void verifyReplicateRegionAfterCreate(final VM memberVM) {
+    memberVM.invoke("verifyReplicateRegionAfterCreate", () -> {
+      Cache cache = getCache_tmp();
 
+      String memberId =
+          MBeanJMXAdapter.getMemberNameOrId(cache.getDistributedSystem().getDistributedMember());
+      ObjectName objectName = ObjectName.getInstance("GemFire:type=Member,member=" + memberId);
 
-  /**
-   * Creates a Distributed Region
-   * 
-   * @param vm
-   */
-  protected void validateReplicateRegionAfterCreate(final VM vm) {
-    SerializableRunnable checkDistributedRegion =
-        new SerializableRunnable("Check Distributed region") {
-          public void run() {
-
-            GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-            SystemManagementService service = (SystemManagementService) getManagementService();
-
-            MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
-            RegionNotif test = new RegionNotif();
-
-            String memberId = MBeanJMXAdapter
-                .getMemberNameOrId(cache.getDistributedSystem().getDistributedMember());
-
-            ObjectName memberMBeanName;
-            try {
-              memberMBeanName = ObjectName.getInstance("GemFire:type=Member,member=" + memberId);
-              mbeanServer.addNotificationListener(memberMBeanName, test, null, null);
-            } catch (MalformedObjectNameException e) {
-
-              Assert.fail("FAILED WITH EXCEPION", e);
-            } catch (NullPointerException e) {
-              Assert.fail("FAILED WITH EXCEPION", e);
-
-            } catch (InstanceNotFoundException e) {
-              Assert.fail("FAILED WITH EXCEPION", e);
+      // List<Notification> notifications = new ArrayList<>();
+      // MEMBER_NOTIFICATIONS_REF.set(notifications);
+      //
+      // MemberNotificationListener listener = new MemberNotificationListener(notifications);
+      // ManagementFactory.getPlatformMBeanServer().addNotificationListener(objectName, listener,
+      // null, null);
 
-            }
+      SystemManagementService service = getSystemManagementService_tmp();
+      RegionMXBean regionMXBean = service.getLocalRegionMBean(REGION_PATH);
+      assertThat(regionMXBean).isNotNull();
 
-            assertNotNull(service.getLocalRegionMBean(REGION_PATH));
+      Region region = cache.getRegion(REGION_PATH);
+      RegionAttributes regionAttributes = region.getAttributes();
 
-            RegionMXBean bean = service.getLocalRegionMBean(REGION_PATH);
-            Region region = cache.getRegion(REGION_PATH);
+      RegionAttributesData regionAttributesData = regionMXBean.listRegionAttributes();
+      verifyRegionAttributes(regionAttributes, regionAttributesData);
 
-            RegionAttributes regAttrs = region.getAttributes();
+      MembershipAttributesData membershipData = regionMXBean.listMembershipAttributes();
+      assertThat(membershipData).isNotNull();
 
-            RegionAttributesData data = bean.listRegionAttributes();
-
-            assertRegionAttributes(regAttrs, data);
-            MembershipAttributesData membershipData = bean.listMembershipAttributes();
-            EvictionAttributesData evictionData = bean.listEvictionAttributes();
-            assertNotNull(membershipData);
-            assertNotNull(evictionData);
-            LogWriterUtils.getLogWriter().info("<ExpectedString> Membership Data is "
-                + membershipData.toString() + "</ExpectedString> ");
-            LogWriterUtils.getLogWriter().info("<ExpectedString> Eviction Data is "
-                + membershipData.toString() + "</ExpectedString> ");
-          }
-        };
-    vm.invoke(checkDistributedRegion);
+      EvictionAttributesData evictionData = regionMXBean.listEvictionAttributes();
+      assertThat(evictionData).isNotNull();
+    });
   }
 
-  /**
-   * Creates a partition Region
-   * 
-   * @param vm
-   */
-  protected void validatePartitionRegionAfterCreate(final VM vm) {
-    SerializableRunnable createParRegion = new SerializableRunnable("Create Partitioned region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        assertNotNull(service.getLocalRegionMBean(PARTITIONED_REGION_PATH));
-        RegionMXBean bean = service.getLocalRegionMBean(PARTITIONED_REGION_PATH);
-        Region partitionedRegion = cache.getRegion(PARTITIONED_REGION_PATH);
-        RegionAttributes regAttrs = partitionedRegion.getAttributes();
-        RegionAttributesData data = bean.listRegionAttributes();
-        PartitionAttributesData parData = bean.listPartitionAttributes();
-        assertPartitionData(regAttrs, parData);
+  private void verifyPartitionRegionAfterCreate(final VM memberVM) {
+    memberVM.invoke("verifyPartitionRegionAfterCreate", () -> {
+      Region region = getCache_tmp().getRegion(PARTITIONED_REGION_PATH);
 
-      }
-    };
-    vm.invoke(createParRegion);
-  }
+      SystemManagementService service = getSystemManagementService_tmp();
+      RegionMXBean regionMXBean = service.getLocalRegionMBean(PARTITIONED_REGION_PATH);
 
-  /**
-   * closes a Distributed Region
-   * 
-   * @param vm
-   */
-  protected void validateReplicatedRegionAfterClose(final VM vm) {
-    SerializableRunnable closeRegion = new SerializableRunnable("Close Distributed region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        RegionMXBean bean = null;
-        try {
-          bean = service.getLocalRegionMBean(REGION_PATH);
-        } catch (ManagementException mgtEx) {
-          LogWriterUtils.getLogWriter().info("<ExpectedString> Expected Exception  "
-              + mgtEx.getLocalizedMessage() + "</ExpectedString> ");
-        }
-        assertNull(bean);
-        ObjectName regionObjectName = service
-            .getRegionMBeanName(cache.getDistributedSystem().getDistributedMember(), REGION_PATH);
-        assertNull(service.getLocalManager().getManagementResourceRepo()
-            .getEntryFromLocalMonitoringRegion(regionObjectName));
-      }
-    };
-    vm.invoke(closeRegion);
+      verifyPartitionData(region.getAttributes(), regionMXBean.listPartitionAttributes());
+    });
   }
 
-  /**
-   * close a partition Region
-   * 
-   * @param vm
-   */
-  protected void validatePartitionRegionAfterClose(final VM vm) {
-    SerializableRunnable closeParRegion = new SerializableRunnable("Close Partition region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        ManagementService service = getManagementService();
-        LogWriterUtils.getLogWriter().info("Closing Par Region");
-        RegionMXBean bean = null;
-        try {
-          bean = service.getLocalRegionMBean(PARTITIONED_REGION_PATH);
-        } catch (ManagementException mgtEx) {
-          LogWriterUtils.getLogWriter().info("<ExpectedString> Expected Exception  "
-              + mgtEx.getLocalizedMessage() + "</ExpectedString> ");
-        }
-        assertNull(bean);
-      }
-    };
-    vm.invoke(closeParRegion);
+  private void verifyReplicatedRegionAfterClose(final VM memberVM) {
+    memberVM.invoke("verifyReplicatedRegionAfterClose", () -> {
+      SystemManagementService service = getSystemManagementService_tmp();
+      RegionMXBean regionMXBean = service.getLocalRegionMBean(REGION_PATH);
+      assertThat(regionMXBean).isNull();
+
+      ObjectName objectName = service.getRegionMBeanName(
+          getCache_tmp().getDistributedSystem().getDistributedMember(), REGION_PATH);
+      assertThat(service.getLocalManager().getManagementResourceRepo()
+          .getEntryFromLocalMonitoringRegion(objectName)).isNull();
+    });
   }
 
-  /**
-   * Closes Fixed Partition region
-   * 
-   * @param vm
-   */
-  protected void closeFixedPartitionRegion(final VM vm) {
-    SerializableRunnable closeParRegion = new SerializableRunnable("Close Fixed Partition region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        ManagementService service = getManagementService();
-        LogWriterUtils.getLogWriter().info("Closing Fixed Par Region");
-        Region region = cache.getRegion(FIXED_PR_PATH);
-        region.close();
-        RegionMXBean bean = null;
-        try {
-          bean = service.getLocalRegionMBean(FIXED_PR_PATH);
-        } catch (ManagementException mgtEx) {
-          LogWriterUtils.getLogWriter().info("<ExpectedString> Expected Exception  "
-              + mgtEx.getLocalizedMessage() + "</ExpectedString> ");
-        }
-        assertNull(bean);
-      }
-    };
-    vm.invoke(closeParRegion);
+  private void verifyPartitionRegionAfterClose(final VM memberVM) {
+    memberVM.invoke("verifyPartitionRegionAfterClose", () -> {
+      ManagementService service = getManagementService_tmp();
+      RegionMXBean regionMXBean = service.getLocalRegionMBean(PARTITIONED_REGION_PATH);
+      assertThat(regionMXBean).isNull();
+    });
   }
 
   /**
-   * Asserts and verifies all the partition related data
-   * 
-   * @param regAttrs
-   * @param partitionAttributesData
+   * Invoked in member VMs
    */
+  private void verifyPartitionData(final RegionAttributes expectedRegionAttributes,
+      final PartitionAttributesData partitionAttributesData) {
+    PartitionAttributes expectedPartitionAttributes =
+        expectedRegionAttributes.getPartitionAttributes();
 
-  protected static void assertPartitionData(RegionAttributes regAttrs,
-      PartitionAttributesData partitionAttributesData) {
-    PartitionAttributesData data = partitionAttributesData;
+    assertThat(partitionAttributesData.getRedundantCopies())
+        .isEqualTo(expectedPartitionAttributes.getRedundantCopies());
 
-    PartitionAttributes partAttrs = regAttrs.getPartitionAttributes();
+    assertThat(partitionAttributesData.getTotalMaxMemory())
+        .isEqualTo(expectedPartitionAttributes.getTotalMaxMemory());
 
-    int redundantCopies = partAttrs.getRedundantCopies();
-    assertEquals(redundantCopies, data.getRedundantCopies());
-    long totalMaxMemory = partAttrs.getTotalMaxMemory();
-    assertEquals(totalMaxMemory, data.getTotalMaxMemory());
     // Total number of buckets for whole region
-    int totalNumBuckets = partAttrs.getTotalNumBuckets();
-    assertEquals(totalNumBuckets, data.getTotalNumBuckets());
+    assertThat(partitionAttributesData.getTotalNumBuckets())
+        .isEqualTo(expectedPartitionAttributes.getTotalNumBuckets());
 
-    int localMaxMemory = partAttrs.getLocalMaxMemory();
-    assertEquals(localMaxMemory, data.getLocalMaxMemory());
+    assertThat(partitionAttributesData.getLocalMaxMemory())
+        .isEqualTo(expectedPartitionAttributes.getLocalMaxMemory());
 
-    String colocatedWith = partAttrs.getColocatedWith();
-    assertEquals(colocatedWith, data.getColocatedWith());
+    assertThat(partitionAttributesData.getColocatedWith())
+        .isEqualTo(expectedPartitionAttributes.getColocatedWith());
 
     String partitionResolver = null;
-    if (partAttrs.getPartitionResolver() != null) {
-      partitionResolver = partAttrs.getPartitionResolver().getName();
+    if (expectedPartitionAttributes.getPartitionResolver() != null) { // TODO: these conditionals
+                                                                      // should be deterministic
+      partitionResolver = expectedPartitionAttributes.getPartitionResolver().getName();
     }
+    assertThat(partitionAttributesData.getPartitionResolver()).isEqualTo(partitionResolver);
 
-    assertEquals(partitionResolver, data.getPartitionResolver());
+    assertThat(partitionAttributesData.getRecoveryDelay())
+        .isEqualTo(expectedPartitionAttributes.getRecoveryDelay());
 
-    long recoveryDelay = partAttrs.getRecoveryDelay();
-    assertEquals(recoveryDelay, data.getRecoveryDelay());
+    assertThat(partitionAttributesData.getStartupRecoveryDelay())
+        .isEqualTo(expectedPartitionAttributes.getStartupRecoveryDelay());
 
-    long startupRecoveryDelay = partAttrs.getStartupRecoveryDelay();
-    assertEquals(startupRecoveryDelay, data.getStartupRecoveryDelay());
+    if (expectedPartitionAttributes.getPartitionListeners() != null) {
+      for (int i = 0; i < expectedPartitionAttributes.getPartitionListeners().length; i++) {
+        // assertEquals((expectedPartitionAttributes.getPartitionListeners())[i].getClass().getCanonicalName(),
+        // partitionAttributesData.getPartitionListeners()[i]);
+        assertThat(partitionAttributesData.getPartitionListeners()[i]).isEqualTo(
+            expectedPartitionAttributes.getPartitionListeners()[i].getClass().getCanonicalName());
 
-    if (partAttrs.getPartitionListeners() != null) {
-      for (int i = 0; i < partAttrs.getPartitionListeners().length; i++) {
-        assertEquals((partAttrs.getPartitionListeners())[i].getClass().getCanonicalName(),
-            data.getPartitionListeners()[i]);
       }
-
     }
-
   }
 
   /**
-   * Checks all Region Attributes
-   * 
-   * @param regAttrs
-   * @param data
+   * Invoked in member VMs
    */
-  protected static void assertRegionAttributes(RegionAttributes regAttrs,
-      RegionAttributesData data) {
-
+  private void verifyRegionAttributes(final RegionAttributes regionAttributes,
+      final RegionAttributesData regionAttributesData) {
     String compressorClassName = null;
-    if (regAttrs.getCompressor() != null) {
-      compressorClassName = regAttrs.getCompressor().getClass().getCanonicalName();
+    if (regionAttributes.getCompressor() != null) { // TODO: these conditionals should be
+                                                    // deterministic
+      compressorClassName = regionAttributes.getCompressor().getClass().getCanonicalName();
     }
-    assertEquals(compressorClassName, data.getCompressorClassName());
+    assertThat(regionAttributesData.getCompressorClassName()).isEqualTo(compressorClassName);
+
     String cacheLoaderClassName = null;
-    if (regAttrs.getCacheLoader() != null) {
-      cacheLoaderClassName = regAttrs.getCacheLoader().getClass().getCanonicalName();
+    if (regionAttributes.getCacheLoader() != null) {
+      cacheLoaderClassName = regionAttributes.getCacheLoader().getClass().getCanonicalName();
     }
-    assertEquals(cacheLoaderClassName, data.getCacheLoaderClassName());
+    assertThat(regionAttributesData.getCacheLoaderClassName()).isEqualTo(cacheLoaderClassName);
+
     String cacheWriteClassName = null;
-    if (regAttrs.getCacheWriter() != null) {
-      cacheWriteClassName = regAttrs.getCacheWriter().getClass().getCanonicalName();
+    if (regionAttributes.getCacheWriter() != null) {
+      cacheWriteClassName = regionAttributes.getCacheWriter().getClass().getCanonicalName();
     }
-    assertEquals(cacheWriteClassName, data.getCacheWriterClassName());
+    assertThat(regionAttributesData.getCacheWriterClassName()).isEqualTo(cacheWriteClassName);
+
     String keyConstraintClassName = null;
-    if (regAttrs.getKeyConstraint() != null) {
-      keyConstraintClassName = regAttrs.getKeyConstraint().getName();
+    if (regionAttributes.getKeyConstraint() != null) {
+      keyConstraintClassName = regionAttributes.getKeyConstraint().getName();
     }
-    assertEquals(keyConstraintClassName, data.getKeyConstraintClassName());
+    assertThat(regionAttributesData.getKeyConstraintClassName()).isEqualTo(keyConstraintClassName);
+
     String valueContstaintClassName = null;
-    if (regAttrs.getValueConstraint() != null) {
-      valueContstaintClassName = regAttrs.getValueConstraint().getName();
+    if (regionAttributes.getValueConstraint() != null) {
+      valueContstaintClassName = regionAttributes.getValueConstraint().getName();
     }
-    assertEquals(valueContstaintClassName, data.getValueConstraintClassName());
-    CacheListener[] listeners = regAttrs.getCacheListeners();
-
+    assertThat(regionAttributesData.getValueConstraintClassName())
+        .isEqualTo(valueContstaintClassName);
 
+    CacheListener[] listeners = regionAttributes.getCacheListeners();
     if (listeners != null) {
-      String[] value = data.getCacheListeners();
+      String[] value = regionAttributesData.getCacheListeners();
       for (int i = 0; i < listeners.length; i++) {
-        assertEquals(value[i], listeners[i].getClass().getName());
+        assertThat(listeners[i].getClass().getName()).isEqualTo(value[i]);
       }
-
     }
 
+    assertThat(regionAttributesData.getRegionTimeToLive())
+        .isEqualTo(regionAttributes.getRegionTimeToLive().getTimeout());
 
+    assertThat(regionAttributesData.getRegionIdleTimeout())
+        .isEqualTo(regionAttributes.getRegionIdleTimeout().getTimeout());
 
-    int regionTimeToLive = regAttrs.getRegionTimeToLive().getTimeout();
-
-    assertEquals(regionTimeToLive, data.getRegionTimeToLive());
-
-    int regionIdleTimeout = regAttrs.getRegionIdleTimeout().getTimeout();
-
-    assertEquals(regionIdleTimeout, data.getRegionIdleTimeout());
+    assertThat(regionAttributesData.getEntryTimeToLive())
+        .isEqualTo(regionAttributes.getEntryTimeToLive().getTimeout());
 
-    int entryTimeToLive = regAttrs.getEntryTimeToLive().getTimeout();
+    assertThat(regionAttributesData.getEntryIdleTimeout())
+        .isEqualTo(regionAttributes.getEntryIdleTimeout().getTimeout());
 
-    assertEquals(entryTimeToLive, data.getEntryTimeToLive());
-
-    int entryIdleTimeout = regAttrs.getEntryIdleTimeout().getTimeout();
-
-    assertEquals(entryIdleTimeout, data.getEntryIdleTimeout());
     String customEntryTimeToLive = null;
-    Object o1 = regAttrs.getCustomEntryTimeToLive();
+    Object o1 = regionAttributes.getCustomEntryTimeToLive();
     if (o1 != null) {
       customEntryTimeToLive = o1.toString();
     }
-    assertEquals(customEntryTimeToLive, data.getCustomEntryTimeToLive());
+    assertThat(regionAttributesData.getCustomEntryTimeToLive()).isEqualTo(customEntryTimeToLive);
 
     String customEntryIdleTimeout = null;
-    Object o2 = regAttrs.getCustomEntryIdleTimeout();
+    Object o2 = regionAttributes.getCustomEntryIdleTimeout();
     if (o2 != null) {
       customEntryIdleTimeout = o2.toString();
     }
-    assertEquals(customEntryIdleTimeout, data.getCustomEntryIdleTimeout());
+    assertThat(regionAttributesData.getCustomEntryIdleTimeout()).isEqualTo(customEntryIdleTimeout);
 
-    boolean ignoreJTA = regAttrs.getIgnoreJTA();
-    assertEquals(ignoreJTA, data.isIgnoreJTA());
+    assertThat(regionAttributesData.isIgnoreJTA()).isEqualTo(regionAttributes.getIgnoreJTA());
 
-    String dataPolicy = regAttrs.getDataPolicy().toString();
-    assertEquals(dataPolicy, data.getDataPolicy());
+    assertThat(regionAttributesData.getDataPolicy())
+        .isEqualTo(regionAttributes.getDataPolicy().toString());
 
-    String scope = regAttrs.getScope().toString();
-    assertEquals(scope, data.getScope());
+    assertThat(regionAttributesData.getScope()).isEqualTo(regionAttributes.getScope().toString());
 
-    int initialCapacity = regAttrs.getInitialCapacity();
-    assertEquals(initialCapacity, data.getInitialCapacity());
-    float loadFactor = regAttrs.getLoadFactor();
-    assertEquals(loadFactor, data.getLoadFactor(), 0);
+    assertThat(regionAttributesData.getInitialCapacity())
+        .isEqualTo(regionAttributes.getInitialCapacity());
 
-    boolean lockGrantor = regAttrs.isLockGrantor();
-    assertEquals(lockGrantor, data.isLockGrantor());
+    assertThat(regionAttributesData.getLoadFactor()).isEqualTo(regionAttributes.getLoadFactor());
 
-    boolean multicastEnabled = regAttrs.getMulticastEnabled();
-    assertEquals(multicastEnabled, data.isMulticastEnabled());
+    assertThat(regionAttributesData.isLockGrantor()).isEqualTo(regionAttributes.isLockGrantor());
 
-    int concurrencyLevel = regAttrs.getConcurrencyLevel();
-    assertEquals(concurrencyLevel, data.getConcurrencyLevel());
+    assertThat(regionAttributesData.isMulticastEnabled())
+        .isEqualTo(regionAttributes.getMulticastEnabled());
 
-    boolean indexMaintenanceSynchronous = regAttrs.getIndexMaintenanceSynchronous();
-    assertEquals(indexMaintenanceSynchronous, data.isIndexMaintenanceSynchronous());
+    assertThat(regionAttributesData.getConcurrencyLevel())
+        .isEqualTo(regionAttributes.getConcurrencyLevel());
 
-    boolean statisticsEnabled = regAttrs.getStatisticsEnabled();
+    assertThat(regionAttributesData.isIndexMaintenanceSynchronous())
+        .isEqualTo(regionAttributes.getIndexMaintenanceSynchronous());
 
-    assertEquals(statisticsEnabled, data.isStatisticsEnabled());
+    assertThat(regionAttributesData.isStatisticsEnabled())
+        .isEqualTo(regionAttributes.getStatisticsEnabled());
 
-    boolean subsciptionConflationEnabled = regAttrs.getEnableSubscriptionConflation();
-    assertEquals(subsciptionConflationEnabled, data.isSubscriptionConflationEnabled());
+    assertThat(regionAttributesData.isSubscriptionConflationEnabled())
+        .isEqualTo(regionAttributes.getEnableSubscriptionConflation());
 
-    boolean asyncConflationEnabled = regAttrs.getEnableAsyncConflation();
-    assertEquals(asyncConflationEnabled, data.isAsyncConflationEnabled());
+    assertThat(regionAttributesData.isAsyncConflationEnabled())
+        .isEqualTo(regionAttributes.getEnableAsyncConflation());
 
-    String poolName = regAttrs.getPoolName();
-    assertEquals(poolName, data.getPoolName());
+    assertThat(regionAttributesData.getPoolName()).isEqualTo(regionAttributes.getPoolName());
 
-    boolean isCloningEnabled = regAttrs.getCloningEnabled();
-    assertEquals(isCloningEnabled, data.isCloningEnabled());
+    assertThat(regionAttributesData.isCloningEnabled())
+        .isEqualTo(regionAttributes.getCloningEnabled());
 
-    String diskStoreName = regAttrs.getDiskStoreName();
-    assertEquals(diskStoreName, data.getDiskStoreName());
+    assertThat(regionAttributesData.getDiskStoreName())
+        .isEqualTo(regionAttributes.getDiskStoreName());
 
     String interestPolicy = null;
-    if (regAttrs.getSubscriptionAttributes() != null) {
-      interestPolicy = regAttrs.getSubscriptionAttributes().getInterestPolicy().toString();
+    if (regionAttributes.getSubscriptionAttributes() != null) {
+      interestPolicy = regionAttributes.getSubscriptionAttributes().getInterestPolicy().toString();
     }
-    assertEquals(interestPolicy, data.getInterestPolicy());
-    boolean diskSynchronus = regAttrs.isDiskSynchronous();
-    assertEquals(diskSynchronus, data.isDiskSynchronous());
+    assertThat(regionAttributesData.getInterestPolicy()).isEqualTo(interestPolicy);
+
+    assertThat(regionAttributesData.isDiskSynchronous())
+        .isEqualTo(regionAttributes.isDiskSynchronous());
   }
 
-  /**
-   * Verifies Region related Statistics
-   */
-  public void verifyStatistics() {
+  private void verifyRemoteFixedPartitionRegion(final VM managerVM) throws Exception {
+    managerVM.invoke("Verify Partition region", () -> {
+      Set<DistributedMember> otherMemberSet = getOtherNormalMembers_tmp();
+
+      for (DistributedMember member : otherMemberSet) {
+        RegionMXBean bean = awaitRegionMXBeanProxy(member, FIXED_PR_PATH);
+
+        PartitionAttributesData data = bean.listPartitionAttributes();
+        assertThat(data).isNotNull();
+
+        FixedPartitionAttributesData[] fixedPrData = bean.listFixedPartitionAttributes();
+        assertThat(fixedPrData).isNotNull();
+        assertThat(fixedPrData).hasSize(3);
+
+        for (int i = 0; i < fixedPrData.length; i++) {
+          // LogWriterUtils.getLogWriter().info("<ExpectedString> Remote PR Data is " +
+          // fixedPrData[i] + "</ExpectedString> ");
+        }
+      }
+    });
+  }
+
+  private void createDistributedRegion_tmp(final VM vm, final String regionName) {
+    vm.invoke(() -> createDistributedRegion_tmp(regionName));
+  }
+
+  private void createDistributedRegion_tmp(final String regionName) {
+    getCache_tmp().createRegionFactory(RegionShortcut.REPLICATE).create(regionName);
+  }
+
+  private void createPartitionRegion_tmp(final VM vm, final String partitionRegionName) {
+    vm.invoke("Create Partitioned region", () -> {
+      SystemManagementService service = getSystemManagementService_tmp();
+      RegionFactory regionFactory =
+          getCache_tmp().createRegionFactory(RegionShortcut.PARTITION_REDUNDANT);
+      regionFactory.create(partitionRegionName);
+    });
+  }
+
+  private void createLocalRegion_tmp(final VM vm, final String localRegionName) {
+    vm.invoke("Create Local region", () -> {
+      SystemManagementService service = getSystemManagementService_tmp();
+      RegionFactory regionFactory = getCache_tmp().createRegionFactory(RegionShortcut.LOCAL);
+      regionFactory.create(localRegionName);
+    });
+  }
 
+  private void createSubRegion_tmp(final VM vm, final String parentRegionPath,
+      final String subregionName) {
+    vm.invoke("Create Sub region", () -> {
+      SystemManagementService service = getSystemManagementService_tmp();
+      Region region = getCache_tmp().getRegion(parentRegionPath);
+      region.createSubregion(subregionName, region.getAttributes());
+    });
   }
 
+  private String getDistributedMemberId_tmp(final VM vm) {
+    return vm.invoke("getMemberId",
+        () -> getCache_tmp().getDistributedSystem().getDistributedMember().getId());
+  }
+
+  private DistributedMember getDistributedMember_tmp(final VM anyVM) {
+    return anyVM.invoke("getDistributedMember_tmp",
+        () -> getCache_tmp().getDistributedSystem().getDistributedMember());
+  }
+
+  private SystemManagementService getSystemManagementService_tmp() {
+    return (SystemManagementService) getManagementService_tmp();
+  }
+
+  private DM getDistributionManager_tmp() {
+    return ((GemFireCacheImpl) getCache_tmp()).getDistributionManager();
+  }
+
+  private DistributedMember getDistributedMember_tmp() {
+    return getCache_tmp().getDistributedSystem().getDistributedMember();
+  }
+
+  private Set<DistributedMember> getOtherNormalMembers_tmp() {
+    Set<DistributedMember> allMembers =
+        new HashSet<>(getDistributionManager_tmp().getNormalDistributionManagerIds());
+    allMembers.remove(getDistributedMember_tmp());
+    return allMembers;
+  }
+
+  private void awaitMemberCount(final int expectedCount) {
+    DistributedSystemMXBean distributedSystemMXBean = awaitDistributedSystemMXBean();
+    await()
+        .until(() -> assertThat(distributedSystemMXBean.getMemberCount()).isEqualTo(expectedCount));
+  }
+
+  private DistributedRegionMXBean awaitDistributedRegionMXBean(final String name) {
+    SystemManagementService service = getSystemManagementService_tmp();
+
+    await().until(() -> assertThat(service.getDistributedRegionMXBean(name)).isNotNull());
+
+    return service.getDistributedRegionMXBean(name);
+  }
+
+  private DistributedRegionMXBean awaitDistributedRegionMXBean(final String name,
+      final int memberCount) {
+    SystemManagementService service = getSystemManagementService_tmp();
+
+    await().until(() -> assertThat(service.getDistributedRegionMXBean(name)).isNotNull());
+    await().until(() -> assertThat(service.getDistributedRegionMXBean(name).getMemberCount())
+        .isEqualTo(memberCount));
+
+    return service.getDistributedRegionMXBean(name);
+  }
+
+  private RegionMXBean awaitRegionMXBeanProxy(final DistributedMember member, final String name) {
+    SystemManagementService service = getSystemManagementService_tmp();
+    ObjectName objectName = service.getRegionMBeanName(member, name);
+    String alias = "awaiting RegionMXBean proxy for " + member;
+
+    await(alias)
+        .until(() -> assertThat(service.getMBeanProxy(objectName, RegionMXBean.class)).isNotNull());
+
+    return service.getMBeanProxy(objectName, RegionMXBean.class);
+  }
+
+  private RegionMXBean awaitRegionMXBeanProxy(final ObjectName objectName) {
+    SystemManagementService service = getSystemManagementService_tmp();
+
+    await()
+        .until(() -> assertThat(service.getMBeanProxy(objectName, RegionMXBean.class)).isNotNull());
+
+    return service.getMBeanProxy(objectName, RegionMXBean.class);
+  }
+
+  private MemberMXBean awaitMemberMXBeanProxy(final DistributedMember member) {
+    SystemManagementService service = getSystemManagementService_tmp();
+    ObjectName objectName = service.getMemberMBeanName(member);
+    String alias = "awaiting MemberMXBean proxy for " + member;
+
+    await(alias)
+        .until(() -> assertThat(service.getMBeanProxy(objectName, MemberMXBean.class)).isNotNull());
+
+    return service.getMBeanProxy(objectName, MemberMXBean.class);
+  }
+
+  private MemberMXBean awaitMemberMXBeanProxy(final ObjectName objectName) {
+    SystemManagementService service = getSystemManagementService_tmp();
+    await()
+        .until(() -> assertThat(service.getMBeanProxy(objectName, MemberMXBean.class)).isNotNull());
+    return service.getMBeanProxy(objectName, MemberMXBean.cla

<TRUNCATED>

[7/8] geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/ClientHealthStatsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/ClientHealthStatsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/ClientHealthStatsDUnitTest.java
index a3c8b27..cebfddc 100644
--- a/geode-core/src/test/java/org/apache/geode/management/ClientHealthStatsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/ClientHealthStatsDUnitTest.java
@@ -14,13 +14,25 @@
  */
 package org.apache.geode.management;
 
+import static java.util.concurrent.TimeUnit.*;
 import static org.apache.geode.distributed.ConfigurationProperties.*;
-import static org.apache.geode.test.dunit.Assert.*;
+import static org.apache.geode.test.dunit.Host.*;
+import static org.apache.geode.test.dunit.IgnoredException.*;
+import static org.apache.geode.test.dunit.Invoke.*;
+import static org.apache.geode.test.dunit.NetworkUtils.*;
+import static org.assertj.core.api.Assertions.*;
 
+import java.io.Serializable;
 import java.util.Collection;
-import java.util.Iterator;
 import java.util.Properties;
 
+import javax.management.ObjectName;
+
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
@@ -29,438 +41,374 @@ import org.apache.geode.cache.EntryEvent;
 import org.apache.geode.cache.Region;
 import org.apache.geode.cache.RegionFactory;
 import org.apache.geode.cache.RegionShortcut;
+import org.apache.geode.cache.client.ClientCache;
 import org.apache.geode.cache.client.ClientCacheFactory;
 import org.apache.geode.cache.client.ClientRegionFactory;
 import org.apache.geode.cache.client.ClientRegionShortcut;
 import org.apache.geode.cache.server.CacheServer;
 import org.apache.geode.cache.util.CacheListenerAdapter;
 import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier;
 import org.apache.geode.internal.cache.tier.sockets.CacheClientProxy;
-import org.apache.geode.internal.i18n.LocalizedStrings;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.IgnoredException;
+import org.apache.geode.management.internal.SystemManagementService;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
 import org.apache.geode.test.junit.categories.DistributedTest;
-import org.apache.geode.test.junit.categories.FlakyTest;
 
 /**
  * Client health stats check
  */
 @Category(DistributedTest.class)
-@SuppressWarnings("serial")
-public class ClientHealthStatsDUnitTest extends JUnit4DistributedTestCase {
-
-  private static final String k1 = "k1";
-  private static final String k2 = "k2";
-  private static final String client_k1 = "client-k1";
-  private static final String client_k2 = "client-k2";
+@SuppressWarnings({"serial", "unused"})
+public class ClientHealthStatsDUnitTest implements Serializable {
 
-  /** name of the test region */
-  private static final String REGION_NAME = "ClientHealthStatsDUnitTest_Region";
+  private static final int NUMBER_PUTS = 100;
 
-  private static VM client = null;
-  private static VM client2 = null;
-  private static VM managingNode = null;
+  private static final String KEY1 = "KEY1";
+  private static final String KEY2 = "KEY2";
+  private static final String VALUE1 = "VALUE1";
+  private static final String VALUE2 = "VALUE2";
 
-  private static ManagementTestBase helper = new ManagementTestBase() {};
+  private static final String REGION_NAME =
+      ClientHealthStatsDUnitTest.class.getSimpleName() + "_Region";
 
-  private static int numOfCreates = 0;
-  private static int numOfUpdates = 0;
-  private static int numOfInvalidates = 0;
-  private static boolean lastKeyReceived = false;
+  // client1VM and client2VM VM fields
+  private static ClientCache clientCache;
 
-  private static GemFireCacheImpl cache = null;
+  // TODO: assert following values in each client VM
+  private static int numOfCreates;
+  private static int numOfUpdates;
+  private static int numOfInvalidates;
+  private static boolean lastKeyReceived;
 
-  private VM server = null;
+  private VM managerVM;
+  private VM serverVM;
+  private VM client1VM;
+  private VM client2VM;
 
-  @Override
-  public final void postSetUp() throws Exception {
-    disconnectAllFromDS();
+  private String hostName;
 
-    final Host host = Host.getHost(0);
-    managingNode = host.getVM(0);
-    server = host.getVM(1);
-    client = host.getVM(2);
-    client2 = host.getVM(3);
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().build();
 
-    IgnoredException.addIgnoredException("Connection reset");
-  }
+  @Before
+  public void before() throws Exception {
+    this.hostName = getServerHostName(getHost(0));
 
-  @Override
-  public final void preTearDown() throws Exception {
-    reset();
-    helper.closeCache(managingNode);
-    helper.closeCache(client);
-    helper.closeCache(client2);
-    helper.closeCache(server);
+    this.managerVM = getHost(0).getVM(0);
+    this.serverVM = getHost(0).getVM(1);
+    this.client1VM = getHost(0).getVM(2);
+    this.client2VM = getHost(0).getVM(3);
 
-    disconnectAllFromDS();
+    addIgnoredException("Connection reset");
   }
 
-  private static void reset() throws Exception {
-    lastKeyReceived = false;
-    numOfCreates = 0;
-    numOfUpdates = 0;
-    numOfInvalidates = 0;
+  @After
+  public void after() throws Exception {
+    invokeInEveryVM(() -> {
+      lastKeyReceived = false;
+      numOfCreates = 0;
+      numOfUpdates = 0;
+      numOfInvalidates = 0;
+      clientCache = null;
+    });
   }
 
   @Test
   public void testClientHealthStats_SubscriptionEnabled() throws Exception {
-    helper.createManagementCache(managingNode);
-    helper.startManagingNode(managingNode);
+    this.managementTestRule.createManager(this.managerVM, false);
+    this.managementTestRule.startManager(this.managerVM);
 
-    int port = (Integer) server.invoke(() -> ClientHealthStatsDUnitTest.createServerCache());
+    int port = this.serverVM.invoke(() -> createServerCache());
 
-    DistributedMember serverMember = helper.getMember(server);
+    this.client1VM.invoke(() -> createClientCache(this.hostName, port, 1, true));
+    this.client2VM.invoke(() -> createClientCache(this.hostName, port, 2, true));
 
-    client.invoke(
-        () -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 1, true, false));
+    this.client1VM.invoke(() -> put());
+    this.client2VM.invoke(() -> put());
 
-    client2.invoke(
-        () -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 2, true, false));
+    DistributedMember serverMember = this.managementTestRule.getDistributedMember(this.serverVM);
+    this.managerVM.invoke(() -> verifyClientStats(serverMember, port, 2));
 
-    client.invoke(() -> ClientHealthStatsDUnitTest.put());
-    client2.invoke(() -> ClientHealthStatsDUnitTest.put());
-
-    managingNode.invoke(() -> ClientHealthStatsDUnitTest.verifyClientStats(serverMember, port, 2));
-    helper.stopManagingNode(managingNode);
+    this.managementTestRule.stopManager(this.managerVM);
   }
 
   @Test
   public void testClientHealthStats_SubscriptionDisabled() throws Exception {
-    helper.createManagementCache(managingNode);
-    helper.startManagingNode(managingNode);
-
-    int port = (Integer) server.invoke(() -> ClientHealthStatsDUnitTest.createServerCache());
-
-    DistributedMember serverMember = helper.getMember(server);
+    this.managementTestRule.createManager(this.managerVM, false);
+    this.managementTestRule.startManager(this.managerVM);
 
-    client.invoke(() -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 1,
-        false, false));
+    int port = this.serverVM.invoke(() -> createServerCache());
 
-    client2.invoke(() -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 2,
-        false, false));
+    this.client1VM.invoke(() -> createClientCache(this.hostName, port, 1, false));
+    this.client2VM.invoke(() -> createClientCache(this.hostName, port, 2, false));
 
-    client.invoke(() -> ClientHealthStatsDUnitTest.put());
-    client2.invoke(() -> ClientHealthStatsDUnitTest.put());
+    this.client1VM.invoke(() -> put());
+    this.client2VM.invoke(() -> put());
 
-    managingNode.invoke(() -> ClientHealthStatsDUnitTest.verifyClientStats(serverMember, port, 0));
-    helper.stopManagingNode(managingNode);
+    DistributedMember serverMember = this.managementTestRule.getDistributedMember(this.serverVM);
+    this.managerVM.invoke(() -> verifyClientStats(serverMember, port, 0));
+    this.managementTestRule.stopManager(this.managerVM);
   }
 
   @Test
   public void testClientHealthStats_DurableClient() throws Exception {
-    helper.createManagementCache(managingNode);
-    helper.startManagingNode(managingNode);
+    this.managementTestRule.createManager(this.managerVM, false);
+    this.managementTestRule.startManager(this.managerVM);
 
-    int port = (Integer) server.invoke(() -> ClientHealthStatsDUnitTest.createServerCache());
+    int port = this.serverVM.invoke(() -> createServerCache());
 
-    DistributedMember serverMember = helper.getMember(server);
+    this.client1VM.invoke(() -> createClientCache(this.hostName, port, 1, true));
+    this.client2VM.invoke(() -> createClientCache(this.hostName, port, 2, true));
 
-    client.invoke(
-        () -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 1, true, true));
+    this.client1VM.invoke(() -> put());
+    this.client2VM.invoke(() -> put());
 
-    client2.invoke(
-        () -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 2, true, true));
+    this.client1VM.invoke(() -> clientCache.close(true));
+    this.client2VM.invoke(() -> clientCache.close(true));
 
-    client.invoke(() -> ClientHealthStatsDUnitTest.put());
-    client2.invoke(() -> ClientHealthStatsDUnitTest.put());
-
-    client.invoke(() -> ClientHealthStatsDUnitTest.closeClientCache());
-
-    client2.invoke(() -> ClientHealthStatsDUnitTest.closeClientCache());
-
-    managingNode.invoke(() -> ClientHealthStatsDUnitTest.verifyClientStats(serverMember, port, 2));
-    helper.stopManagingNode(managingNode);
+    DistributedMember serverMember = this.managementTestRule.getDistributedMember(this.serverVM);
+    this.managerVM.invoke(() -> verifyClientStats(serverMember, port, 2));
+    this.managementTestRule.stopManager(this.managerVM);
   }
 
-  @Category(FlakyTest.class) // GEODE-337
   @Test
   public void testStatsMatchWithSize() throws Exception {
-    // start a server
-    int port = (Integer) server.invoke(() -> ClientHealthStatsDUnitTest.createServerCache());
-    // create durable client, with durable RI
-    client.invoke(
-        () -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 1, true, false));
-    // do puts on server from three different threads, pause after 500 puts each.
-    server.invoke(() -> ClientHealthStatsDUnitTest.doPuts());
-    // close durable client
-    client.invoke(() -> ClientHealthStatsDUnitTest.closeClientCache());
-
-    server.invoke("verifyProxyHasBeenPaused", () -> verifyProxyHasBeenPaused());
-    // resume puts on server, add another 100.
-    server.invokeAsync(() -> ClientHealthStatsDUnitTest.resumePuts());
-    // start durable client
-    client.invoke(
-        () -> ClientHealthStatsDUnitTest.createClientCache(server.getHost(), port, 1, true, false));
-    // wait for full queue dispatch
-    client.invoke(() -> ClientHealthStatsDUnitTest.waitForLastKey());
-    // verify the stats
-    server.invoke(() -> ClientHealthStatsDUnitTest.verifyStats(port));
-  }
+    int port = this.serverVM.invoke(() -> createServerCache()); // start a serverVM
 
-  private static void verifyProxyHasBeenPaused() {
+    this.client1VM.invoke(() -> createClientCache(this.hostName, port, 1, true)); // create durable
+                                                                                  // client1VM, with
+                                                                                  // durable RI
 
-    WaitCriterion criterion = new WaitCriterion() {
+    this.serverVM.invoke(() -> doPuts()); // do puts on serverVM from three different threads, pause
+                                          // after 500 puts each.
 
-      @Override
-      public boolean done() {
-        CacheClientNotifier ccn = CacheClientNotifier.getInstance();
-        Collection<CacheClientProxy> ccProxies = ccn.getClientProxies();
+    this.client1VM.invoke(() -> clientCache.close(true)); // close durable client1VM
 
-        Iterator<CacheClientProxy> itr = ccProxies.iterator();
+    this.serverVM
+        .invoke(() -> await().atMost(2, MINUTES).until(() -> cacheClientProxyHasBeenPause()));
 
-        while (itr.hasNext()) {
-          CacheClientProxy ccp = itr.next();
-          System.out.println("proxy status " + ccp.getState());
-          if (ccp.isPaused())
-            return true;
-        }
-        return false;
-      }
+    this.serverVM.invoke(() -> resumePuts()); // resume puts on serverVM, add another 100.
 
-      @Override
-      public String description() {
-        return "Proxy has not paused yet";
-      }
-    };
+    this.client1VM.invoke(() -> createClientCache(this.hostName, port, 1, true)); // start durable
+                                                                                  // client1VM
+
+    this.client1VM.invoke(() -> await().atMost(1, MINUTES).until(() -> lastKeyReceived)); // wait
+                                                                                          // for
+                                                                                          // full
+                                                                                          // queue
+                                                                                          // dispatch
 
-    Wait.waitForCriterion(criterion, 15 * 1000, 200, true);
+    this.serverVM.invoke(() -> verifyStats(port)); // verify the stats
   }
 
-  private static int createServerCache() throws Exception {
-    Cache cache = helper.createCache(false);
+  /**
+   * Invoked in serverVM
+   */
+  private boolean cacheClientProxyHasBeenPause() {
+    CacheClientNotifier clientNotifier = CacheClientNotifier.getInstance(); // TODO
+    // CacheClientNotifier clientNotifier =
+    // ((CacheServerImpl)this.managementTestRule.getCache().getCacheServers().get(0)).getAcceptor().getCacheClientNotifier();
 
-    RegionFactory<String, String> rf = cache.createRegionFactory(RegionShortcut.REPLICATE);
-    rf.setConcurrencyChecksEnabled(false);
-    rf.create(REGION_NAME);
+    Collection<CacheClientProxy> clientProxies = clientNotifier.getClientProxies();
 
-    CacheServer server1 = cache.addCacheServer();
-    server1.setPort(0);
-    server1.start();
-    return server1.getPort();
+    for (CacheClientProxy clientProxy : clientProxies) {
+      if (clientProxy.isPaused()) {
+        return true;
+      }
+    }
+    return false;
   }
 
-  private static void closeClientCache() throws Exception {
-    cache.close(true);
+  /**
+   * Invoked in serverVM
+   */
+  private int createServerCache() throws Exception {
+    Cache cache = this.managementTestRule.getCache();
+
+    RegionFactory<String, String> regionFactory =
+        cache.createRegionFactory(RegionShortcut.REPLICATE);
+    regionFactory.setConcurrencyChecksEnabled(false);
+    regionFactory.create(REGION_NAME);
+
+    CacheServer cacheServer = cache.addCacheServer();
+    cacheServer.setPort(0);
+    cacheServer.start();
+    return cacheServer.getPort();
   }
 
-  private static void createClientCache(Host host, Integer port, int clientNum,
-      boolean subscriptionEnabled, boolean durable) throws Exception {
+  /**
+   * Invoked in client1VM and client2VM
+   */
+  private void createClientCache(final String hostName, final Integer port, final int clientNum,
+      final boolean subscriptionEnabled) throws Exception {
     Properties props = new Properties();
-    props.setProperty(DURABLE_CLIENT_ID, "durable-" + clientNum);
-    props.setProperty(DURABLE_CLIENT_TIMEOUT, "300000");
-    props.setProperty(LOG_LEVEL, "info");
-    props.setProperty(STATISTIC_ARCHIVE_FILE,
-        getTestMethodName() + "_client_" + clientNum + ".gfs");
     props.setProperty(STATISTIC_SAMPLING_ENABLED, "true");
 
-    ClientCacheFactory ccf = new ClientCacheFactory(props);
+    ClientCacheFactory cacheFactory = new ClientCacheFactory(props);
     if (subscriptionEnabled) {
-      ccf.setPoolSubscriptionEnabled(true);
-      ccf.setPoolSubscriptionAckInterval(50);
-      ccf.setPoolSubscriptionRedundancy(0);
+      cacheFactory.setPoolSubscriptionEnabled(true);
+      cacheFactory.setPoolSubscriptionAckInterval(50);
+      cacheFactory.setPoolSubscriptionRedundancy(0);
     }
 
-    if (durable) {
-      ccf.set(DURABLE_CLIENT_ID, "DurableClientId_" + clientNum);
-      ccf.set(DURABLE_CLIENT_TIMEOUT, "" + 300);
-    }
+    cacheFactory.set(DURABLE_CLIENT_ID, "DurableClientId_" + clientNum);
+    cacheFactory.set(DURABLE_CLIENT_TIMEOUT, "" + 30000);
 
-    ccf.addPoolServer(host.getHostName(), port);
-    cache = (GemFireCacheImpl) ccf.create();
+    cacheFactory.addPoolServer(hostName, port);
+    clientCache = cacheFactory.create();
 
-    ClientRegionFactory<String, String> crf =
-        cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY);
-    crf.setConcurrencyChecksEnabled(false);
+    ClientRegionFactory<String, String> regionFactory =
+        clientCache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY);
+    regionFactory.setConcurrencyChecksEnabled(false);
 
-    crf.addCacheListener(new CacheListenerAdapter<String, String>() {
-      public void afterInvalidate(EntryEvent<String, String> event) {
-        cache.getLoggerI18n()
-            .fine("Invalidate Event: " + event.getKey() + ", " + event.getNewValue());
+    regionFactory.addCacheListener(new CacheListenerAdapter<String, String>() {
+      @Override
+      public void afterInvalidate(final EntryEvent<String, String> event) {
         numOfInvalidates++;
       }
 
-      public void afterCreate(EntryEvent<String, String> event) {
-        if (((String) event.getKey()).equals("last_key")) {
+      @Override
+      public void afterCreate(final EntryEvent<String, String> event) {
+        if ("last_key".equals(event.getKey())) {
           lastKeyReceived = true;
         }
-        cache.getLoggerI18n().fine("Create Event: " + event.getKey() + ", " + event.getNewValue());
         numOfCreates++;
       }
 
-      public void afterUpdate(EntryEvent<String, String> event) {
-        cache.getLoggerI18n().fine("Update Event: " + event.getKey() + ", " + event.getNewValue());
+      @Override
+      public void afterUpdate(final EntryEvent<String, String> event) {
         numOfUpdates++;
       }
     });
 
-    Region<String, String> r = crf.create(REGION_NAME);
+    Region<String, String> region = regionFactory.create(REGION_NAME);
     if (subscriptionEnabled) {
-      r.registerInterest("ALL_KEYS", true);
-      cache.readyForEvents();
+      region.registerInterest("ALL_KEYS", true);
+      clientCache.readyForEvents();
     }
   }
 
-  private static void doPuts() throws Exception {
-    Cache cache = GemFireCacheImpl.getInstance();
-    final Region<String, String> r = cache.getRegion(Region.SEPARATOR + REGION_NAME);
-    Thread t1 = new Thread(new Runnable() {
-      public void run() {
-        for (int i = 0; i < 500; i++) {
-          r.put("T1_KEY_" + i, "VALUE_" + i);
-        }
+  /**
+   * Invoked in serverVM
+   */
+  private void doPuts() throws Exception {
+    Cache cache = this.managementTestRule.getCache();
+    Region<String, String> region = cache.getRegion(Region.SEPARATOR + REGION_NAME);
+
+    Thread thread1 = new Thread(() -> {
+      for (int i = 0; i < NUMBER_PUTS; i++) {
+        region.put("T1_KEY_" + i, "VALUE_" + i);
       }
     });
-    Thread t2 = new Thread(new Runnable() {
-      public void run() {
-        for (int i = 0; i < 500; i++) {
-          r.put("T2_KEY_" + i, "VALUE_" + i);
-        }
+    Thread thread2 = new Thread(() -> {
+      for (int i = 0; i < NUMBER_PUTS; i++) {
+        region.put("T2_KEY_" + i, "VALUE_" + i);
       }
     });
-    Thread t3 = new Thread(new Runnable() {
-      public void run() {
-        for (int i = 0; i < 500; i++) {
-          r.put("T3_KEY_" + i, "VALUE_" + i);
-        }
+    Thread thread3 = new Thread(() -> {
+      for (int i = 0; i < NUMBER_PUTS; i++) {
+        region.put("T3_KEY_" + i, "VALUE_" + i);
       }
     });
 
-    t1.start();
-    t2.start();
-    t3.start();
+    thread1.start();
+    thread2.start();
+    thread3.start();
 
-    t1.join();
-    t2.join();
-    t3.join();
+    thread1.join();
+    thread2.join();
+    thread3.join();
   }
 
-  private static void resumePuts() {
-    Cache cache = GemFireCacheImpl.getInstance();
-    Region<String, String> r = cache.getRegion(Region.SEPARATOR + REGION_NAME);
-    for (int i = 0; i < 100; i++) {
-      r.put("NEWKEY_" + i, "NEWVALUE_" + i);
+  /**
+   * Invoked in serverVM
+   */
+  private void resumePuts() {
+    Cache cache = this.managementTestRule.getCache();
+    Region<String, String> region = cache.getRegion(Region.SEPARATOR + REGION_NAME);
+
+    for (int i = 0; i < NUMBER_PUTS; i++) {
+      region.put("NEWKEY_" + i, "NEWVALUE_" + i);
     }
-    r.put("last_key", "last_value");
+    region.put("last_key", "last_value");
   }
 
-  private static void waitForLastKey() {
-    WaitCriterion wc = new WaitCriterion() {
-      @Override
-      public boolean done() {
-        return lastKeyReceived;
-      }
+  /**
+   * Invoked in managerVM
+   */
+  private void verifyClientStats(final DistributedMember serverMember, final int serverPort,
+      final int numSubscriptions) throws Exception {
+    ManagementService service = this.managementTestRule.getManagementService();
+    CacheServerMXBean cacheServerMXBean = awaitCacheServerMXBean(serverMember, serverPort);
 
-      @Override
-      public String description() {
-        return "Did not receive last key.";
-      }
-    };
-    Wait.waitForCriterion(wc, 60 * 1000, 500, true);
-  }
+    String[] clientIds = cacheServerMXBean.getClientIds();
+    assertThat(clientIds).hasSize(2);
 
-  private static DistributedMember getMember() throws Exception {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    return cache.getDistributedSystem().getDistributedMember();
-  }
+    ClientHealthStatus[] clientStatuses = cacheServerMXBean.showAllClientStats();
 
-  private static void verifyClientStats(DistributedMember serverMember, int serverPort,
-      int numSubscriptions) {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    try {
-      ManagementService service = ManagementService.getExistingManagementService(cache);
-      CacheServerMXBean bean = MBeanUtil.getCacheServerMbeanProxy(serverMember, serverPort);
-
-      String[] clientIds = bean.getClientIds();
-      assertTrue(clientIds.length == 2);
-      System.out.println(
-          "<ExpectedString> ClientId-1 of the Server is  " + clientIds[0] + "</ExpectedString> ");
-      System.out.println(
-          "<ExpectedString> ClientId-2 of the Server is  " + clientIds[1] + "</ExpectedString> ");
-
-      ClientHealthStatus[] clientStatuses = bean.showAllClientStats();
-
-      ClientHealthStatus clientStatus1 = bean.showClientStats(clientIds[0]);
-      ClientHealthStatus clientStatus2 = bean.showClientStats(clientIds[1]);
-      assertNotNull(clientStatus1);
-      assertNotNull(clientStatus2);
-      System.out.println("<ExpectedString> ClientStats-1 of the Server is  " + clientStatus1
-          + "</ExpectedString> ");
-      System.out.println("<ExpectedString> ClientStats-2 of the Server is  " + clientStatus2
-          + "</ExpectedString> ");
-
-      System.out
-          .println("<ExpectedString> clientStatuses " + clientStatuses + "</ExpectedString> ");
-      assertNotNull(clientStatuses);
-
-      assertTrue(clientStatuses.length == 2);
-      for (ClientHealthStatus status : clientStatuses) {
-        System.out.println(
-            "<ExpectedString> ClientStats of the Server is  " + status + "</ExpectedString> ");
-      }
+    ClientHealthStatus clientStatus1 = cacheServerMXBean.showClientStats(clientIds[0]);
+    ClientHealthStatus clientStatus2 = cacheServerMXBean.showClientStats(clientIds[1]);
+    assertThat(clientStatus1).isNotNull();
+    assertThat(clientStatus2).isNotNull();
 
-      DistributedSystemMXBean dsBean = service.getDistributedSystemMXBean();
-      assertEquals(2, dsBean.getNumClients());
-      assertEquals(numSubscriptions, dsBean.getNumSubscriptions());
+    assertThat(clientStatuses).isNotNull().hasSize(2);
 
-    } catch (Exception e) {
-      fail("Error while verifying cache server from remote member", e);
-    }
+    DistributedSystemMXBean dsBean = service.getDistributedSystemMXBean();
+    assertThat(dsBean.getNumClients()).isEqualTo(2);
+    assertThat(dsBean.getNumSubscriptions()).isEqualTo(numSubscriptions);
   }
 
-  private static void put() {
-    Cache cache = GemFireCacheImpl.getInstance();
-    Region r1 = cache.getRegion(Region.SEPARATOR + REGION_NAME);
-    assertNotNull(r1);
-
-    r1.put(k1, client_k1);
-    assertEquals(r1.getEntry(k1).getValue(), client_k1);
-    r1.put(k2, client_k2);
-    assertEquals(r1.getEntry(k2).getValue(), client_k2);
-    try {
-      Thread.sleep(10000);
-    } catch (Exception e) {
-      // sleep
-    }
-    r1.clear();
-
-    r1.put(k1, client_k1);
-    assertEquals(r1.getEntry(k1).getValue(), client_k1);
-    r1.put(k2, client_k2);
-    assertEquals(r1.getEntry(k2).getValue(), client_k2);
-    r1.clear();
-    try {
-      Thread.sleep(10000);
-    } catch (Exception e) {
-      // sleep
-    }
+  /**
+   * Invoked in client1VM and client2VM
+   */
+  private void put() throws Exception {
+    Cache cache = (Cache) clientCache;
+    Region<String, String> region = cache.getRegion(Region.SEPARATOR + REGION_NAME);
+
+    region.put(KEY1, VALUE1);
+    assertThat(region.getEntry(KEY1).getValue()).isEqualTo(VALUE1);
+
+    region.put(KEY2, VALUE2);
+    assertThat(region.getEntry(KEY2).getValue()).isEqualTo(VALUE2);
+
+    region.clear();
+
+    region.put(KEY1, VALUE1);
+    assertThat(region.getEntry(KEY1).getValue()).isEqualTo(VALUE1);
+
+    region.put(KEY2, VALUE2);
+    assertThat(region.getEntry(KEY2).getValue()).isEqualTo(VALUE2);
+
+    region.clear();
   }
 
-  private static void verifyStats(int serverPort) throws Exception {
-    Cache cache = GemFireCacheImpl.getInstance();
-    ManagementService service = ManagementService.getExistingManagementService(cache);
+  /**
+   * Invoked in serverVM
+   */
+  private void verifyStats(final int serverPort) throws Exception {
+    ManagementService service = this.managementTestRule.getManagementService();
     CacheServerMXBean serverBean = service.getLocalCacheServerMXBean(serverPort);
-    CacheClientNotifier ccn = CacheClientNotifier.getInstance();
-    CacheClientProxy ccp = ccn.getClientProxies().iterator().next();
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG, "getQueueSize() " + ccp.getQueueSize());
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
-        "getQueueSizeStat() " + ccp.getQueueSizeStat());
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
-        "getEventsEnqued() " + ccp.getHARegionQueue().getStatistics().getEventsEnqued());
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
-        "getEventsDispatched() " + ccp.getHARegionQueue().getStatistics().getEventsDispatched());
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
-        "getEventsRemoved() " + ccp.getHARegionQueue().getStatistics().getEventsRemoved());
-    cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
-        "getNumVoidRemovals() " + ccp.getHARegionQueue().getStatistics().getNumVoidRemovals());
-    assertEquals(ccp.getQueueSize(), ccp.getQueueSizeStat());
+
+    CacheClientNotifier clientNotifier = CacheClientNotifier.getInstance();
+    CacheClientProxy clientProxy = clientNotifier.getClientProxies().iterator().next();
+    assertThat(clientProxy.getQueueSizeStat()).isEqualTo(clientProxy.getQueueSize());
+
     ClientQueueDetail queueDetails = serverBean.showClientQueueDetails()[0];
-    assertEquals(queueDetails.getQueueSize(), ccp.getQueueSizeStat());
+    assertThat(clientProxy.getQueueSizeStat()).isEqualTo((int) queueDetails.getQueueSize());
+  }
+
+  private CacheServerMXBean awaitCacheServerMXBean(final DistributedMember serverMember,
+      final int port) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    ObjectName objectName = service.getCacheServerMBeanName(port, serverMember);
+
+    await().until(
+        () -> assertThat(service.getMBeanProxy(objectName, CacheServerMXBean.class)).isNotNull());
+
+    return service.getMBeanProxy(objectName, CacheServerMXBean.class);
+  }
+
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(2, MINUTES);
   }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/CompositeTypeTestDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/CompositeTypeTestDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/CompositeTypeTestDUnitTest.java
index 9c33003..cdb55a9 100644
--- a/geode-core/src/test/java/org/apache/geode/management/CompositeTypeTestDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/CompositeTypeTestDUnitTest.java
@@ -14,163 +14,90 @@
  */
 package org.apache.geode.management;
 
-import org.junit.experimental.categories.Category;
-import org.junit.Test;
+import static java.util.concurrent.TimeUnit.*;
+import static org.assertj.core.api.Assertions.*;
 
-import static org.junit.Assert.*;
+import java.io.Serializable;
 
-import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
-import org.apache.geode.test.junit.categories.FlakyTest;
-
-import javax.management.MalformedObjectNameException;
 import javax.management.ObjectName;
 
-import org.apache.geode.internal.cache.GemFireCacheImpl;
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
 import org.apache.geode.management.internal.MBeanJMXAdapter;
-import org.apache.geode.management.internal.ManagementConstants;
 import org.apache.geode.management.internal.SystemManagementService;
-import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
+import org.apache.geode.test.junit.categories.DistributedTest;
 
 @Category(DistributedTest.class)
-public class CompositeTypeTestDUnitTest extends ManagementTestBase {
+@SuppressWarnings({"serial", "unused"})
+public class CompositeTypeTestDUnitTest implements Serializable {
 
-  public CompositeTypeTestDUnitTest() {
-    super();
-    // TODO Auto-generated constructor stub
-  }
+  @Manager
+  private VM managerVM;
 
-  /**
-   * 
-   */
-  private static final long serialVersionUID = 1L;
+  @Member
+  private VM memberVM;
 
-  private static ObjectName objectName;
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().start(true).build();
 
-  @Category(FlakyTest.class) // GEODE-1492
   @Test
   public void testCompositeTypeGetters() throws Exception {
+    registerMBeanWithCompositeTypeGetters(this.memberVM);
 
-    initManagement(false);
-    String member = getMemberId(managedNode1);
-    member = MBeanJMXAdapter.makeCompliantName(member);
-
-    registerMBeanWithCompositeTypeGetters(managedNode1, member);
+    String memberName = MBeanJMXAdapter.makeCompliantName(getMemberId(this.memberVM));
+    verifyMBeanWithCompositeTypeGetters(this.managerVM, memberName);
+  }
 
+  private void registerMBeanWithCompositeTypeGetters(final VM memberVM) throws Exception {
+    memberVM.invoke("registerMBeanWithCompositeTypeGetters", () -> {
+      SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
-    checkMBeanWithCompositeTypeGetters(managingNode, member);
+      ObjectName objectName = new ObjectName("GemFire:service=custom,type=composite");
+      CompositeTestMXBean compositeTestMXBean = new CompositeTestMBean();
 
+      objectName = service.registerMBean(compositeTestMXBean, objectName);
+      service.federate(objectName, CompositeTestMXBean.class, false);
+    });
   }
 
-
-  /**
-   * Creates a Local region
-   *
-   * @param vm reference to VM
-   */
-  protected void registerMBeanWithCompositeTypeGetters(VM vm, final String memberID)
+  private void verifyMBeanWithCompositeTypeGetters(final VM managerVM, final String memberId)
       throws Exception {
-    SerializableRunnable regMBean =
-        new SerializableRunnable("Register CustomMBean with composite Type") {
-          public void run() {
-            GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-            SystemManagementService service = (SystemManagementService) getManagementService();
-
-            try {
-              ObjectName objectName = new ObjectName("GemFire:service=custom,type=composite");
-              CompositeTestMXBean mbean = new CompositeTestMBean();
-              objectName = service.registerMBean(mbean, objectName);
-              service.federate(objectName, CompositeTestMXBean.class, false);
-            } catch (MalformedObjectNameException e) {
-              // TODO Auto-generated catch block
-              e.printStackTrace();
-            } catch (NullPointerException e) {
-              // TODO Auto-generated catch block
-              e.printStackTrace();
-            }
-
-
-
-          }
-        };
-    vm.invoke(regMBean);
-  }
+    managerVM.invoke("verifyMBeanWithCompositeTypeGetters", () -> {
+      SystemManagementService service = this.managementTestRule.getSystemManagementService();
+      ObjectName objectName =
+          new ObjectName("GemFire:service=custom,type=composite,member=" + memberId);
+
+      await().until(() -> service.getMBeanInstance(objectName, CompositeTestMXBean.class) != null);
+
+      CompositeTestMXBean compositeTestMXBean =
+          service.getMBeanInstance(objectName, CompositeTestMXBean.class);
+      assertThat(compositeTestMXBean).isNotNull();
 
+      CompositeStats listCompositeStatsData = compositeTestMXBean.listCompositeStats();
+      assertThat(listCompositeStatsData).isNotNull();
 
-  /**
-   * Creates a Local region
-   *
-   * @param vm reference to VM
-   */
-  protected void checkMBeanWithCompositeTypeGetters(VM vm, final String memberID) throws Exception {
-    SerializableRunnable checkMBean =
-        new SerializableRunnable("Check CustomMBean with composite Type") {
-          public void run() {
-            GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-            final SystemManagementService service =
-                (SystemManagementService) getManagementService();
-
-            try {
-              final ObjectName objectName =
-                  new ObjectName("GemFire:service=custom,type=composite,member=" + memberID);
-
-              Wait.waitForCriterion(new WaitCriterion() {
-                public String description() {
-                  return "Waiting for Composite Type MBean";
-                }
-
-                public boolean done() {
-                  CompositeTestMXBean bean =
-                      service.getMBeanInstance(objectName, CompositeTestMXBean.class);
-                  boolean done = (bean != null);
-                  return done;
-                }
-
-              }, ManagementConstants.REFRESH_TIME * 4, 500, true);
-
-
-              CompositeTestMXBean bean =
-                  service.getMBeanInstance(objectName, CompositeTestMXBean.class);
-
-              CompositeStats listData = bean.listCompositeStats();
-
-              System.out.println("connectionStatsType = " + listData.getConnectionStatsType());
-              System.out.println("connectionsOpened = " + listData.getConnectionsOpened());
-              System.out.println("connectionsClosed = " + listData.getConnectionsClosed());
-              System.out.println("connectionsAttempted = " + listData.getConnectionsAttempted());
-              System.out.println("connectionsFailed = " + listData.getConnectionsFailed());
-
-              CompositeStats getsData = bean.getCompositeStats();
-              System.out.println("connectionStatsType = " + getsData.getConnectionStatsType());
-              System.out.println("connectionsOpened = " + getsData.getConnectionsOpened());
-              System.out.println("connectionsClosed = " + getsData.getConnectionsClosed());
-              System.out.println("connectionsAttempted = " + getsData.getConnectionsAttempted());
-              System.out.println("connectionsFailed = " + getsData.getConnectionsFailed());
-
-              CompositeStats[] arrayData = bean.getCompositeArray();
-              Integer[] intArrayData = bean.getIntegerArray();
-              Thread.sleep(2 * 60 * 1000);
-            } catch (MalformedObjectNameException e) {
-              // TODO Auto-generated catch block
-              e.printStackTrace();
-            } catch (NullPointerException e) {
-              // TODO Auto-generated catch block
-              e.printStackTrace();
-            } catch (InterruptedException e) {
-              // TODO Auto-generated catch block
-              e.printStackTrace();
-            }
-
-
-
-          }
-        };
-    vm.invoke(checkMBean);
+      CompositeStats getCompositeStatsData = compositeTestMXBean.getCompositeStats();
+      assertThat(getCompositeStatsData).isNotNull();
+
+      CompositeStats[] getCompositeArrayData = compositeTestMXBean.getCompositeArray();
+      assertThat(getCompositeArrayData).isNotNull().isNotEmpty();
+
+      Integer[] getIntegerArrayData = compositeTestMXBean.getIntegerArray();
+      assertThat(getIntegerArrayData).isNotNull().isNotEmpty();
+    });
   }
 
+  private String getMemberId(final VM memberVM) {
+    return memberVM.invoke("getMemberId",
+        () -> this.managementTestRule.getDistributedMember().getId());
+  }
 
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(2, MINUTES);
+  }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/DLockManagementDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/DLockManagementDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/DLockManagementDUnitTest.java
index 86501c3..cc8e611 100644
--- a/geode-core/src/test/java/org/apache/geode/management/DLockManagementDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/DLockManagementDUnitTest.java
@@ -14,452 +14,289 @@
  */
 package org.apache.geode.management;
 
-import org.junit.experimental.categories.Category;
-import org.junit.Test;
-
-import static org.junit.Assert.*;
-
-import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
+import static java.util.concurrent.TimeUnit.*;
+import static org.apache.geode.internal.process.ProcessUtils.*;
+import static org.assertj.core.api.Assertions.*;
 
+import java.io.Serializable;
 import java.util.Map;
 import java.util.Set;
 
 import javax.management.ObjectName;
 
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
+import org.junit.Rule;
+import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
 import org.apache.geode.distributed.DistributedLockService;
 import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.InternalDistributedSystem;
 import org.apache.geode.distributed.internal.locks.DLockService;
-import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.management.internal.MBeanJMXAdapter;
 import org.apache.geode.management.internal.SystemManagementService;
-import org.apache.geode.test.dunit.Assert;
-import org.apache.geode.test.dunit.LogWriterUtils;
-import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
-import org.apache.geode.test.junit.categories.FlakyTest;
+import org.apache.geode.test.junit.categories.DistributedTest;
 
 @Category(DistributedTest.class)
-public class DLockManagementDUnitTest extends ManagementTestBase {
+@SuppressWarnings({"serial", "unused"})
+public class DLockManagementDUnitTest implements Serializable {
 
-  private static final long serialVersionUID = 1L;
+  private static final int MAX_WAIT_MILLIS = 120 * 1000; // 2 MINUTES
 
-  private static final String LOCK_SERVICE_NAME = "testLockService";
+  private static final String LOCK_SERVICE_NAME =
+      DLockManagementDUnitTest.class.getSimpleName() + "_testLockService";
 
-  // This must be bigger than the dunit ack-wait-threshold for the revoke
-  // tests. The command line is setting the ack-wait-threshold to be
-  // 60 seconds.
-  private static final int MAX_WAIT = 70 * 1000;
+  @Manager
+  private VM managerVM;
 
-  public DLockManagementDUnitTest() {
-    super();
+  @Member
+  private VM[] memberVMs;
 
-  }
+  @Rule
+  public ManagementTestRule managementTestRule =
+      ManagementTestRule.builder().managersFirst(false).start(true).build();
 
-  /**
-   * Distributed Lock Service test
-   * 
-   * @throws Exception
-   */
-  @Category(FlakyTest.class) // GEODE-173: eats exceptions, HeadlessGFSH, time sensitive,
-                             // waitForCriterions
   @Test
-  public void testDLockMBean() throws Throwable {
-
-    initManagement(false);
+  public void testLockServiceMXBean() throws Throwable {
+    createLockServiceGrantor(this.memberVMs[0]);
+    createLockService(this.memberVMs[1]);
+    createLockService(this.memberVMs[2]);
 
-    VM[] managedNodes = new VM[getManagedNodeList().size()];
-    VM managingNode = getManagingNode();
-
-    getManagedNodeList().toArray(managedNodes);
-
-    createGrantorLockService(managedNodes[0]);
-
-    createLockService(managedNodes[1]);
-
-    createLockService(managedNodes[2]);
-
-    for (VM vm : getManagedNodeList()) {
-      verifyLockData(vm);
+    for (VM memberVM : this.memberVMs) {
+      verifyLockServiceMXBeanInMember(memberVM);
     }
-    verifyLockDataRemote(managingNode);
+    verifyLockServiceMXBeanInManager(this.managerVM);
 
-    for (VM vm : getManagedNodeList()) {
-      closeLockService(vm);
+    for (VM memberVM : this.memberVMs) {
+      closeLockService(memberVM);
     }
   }
 
-  /**
-   * Distributed Lock Service test
-   * 
-   * @throws Exception
-   */
-  @Category(FlakyTest.class) // GEODE-553: waitForCriterion, eats exceptions, HeadlessGFSH
   @Test
-  public void testDLockAggregate() throws Throwable {
-    initManagement(false);
-    VM[] managedNodes = new VM[getManagedNodeList().size()];
-    VM managingNode = getManagingNode();
-
-    getManagedNodeList().toArray(managedNodes);
-
-    createGrantorLockService(managedNodes[0]);
-
-    createLockService(managedNodes[1]);
+  public void testDistributedLockServiceMXBean() throws Throwable {
+    createLockServiceGrantor(this.memberVMs[0]);
+    createLockService(this.memberVMs[1]);
+    createLockService(this.memberVMs[2]);
 
-    createLockService(managedNodes[2]);
+    verifyDistributedLockServiceMXBean(this.managerVM, 3);
 
-    checkAggregate(managingNode, 3);
-    DistributedMember member = getMember(managedNodes[2]);
-    checkNavigation(managingNode, member);
+    DistributedMember member = this.managementTestRule.getDistributedMember(this.memberVMs[2]);
+    verifyFetchOperations(this.managerVM, member);
 
-    createLockService(managingNode);
-    checkAggregate(managingNode, 4);
+    createLockService(this.managerVM);
+    verifyDistributedLockServiceMXBean(this.managerVM, 4);
 
-
-    for (VM vm : getManagedNodeList()) {
-      closeLockService(vm);
+    for (VM memberVM : this.memberVMs) {
+      closeLockService(memberVM);
     }
-    ensureProxyCleanup(managingNode);
-    checkAggregate(managingNode, 1);
-    closeLockService(managingNode);
-    checkAggregate(managingNode, 0);
+    verifyProxyCleanupInManager(this.managerVM);
+    verifyDistributedLockServiceMXBean(this.managerVM, 1);
 
+    closeLockService(this.managerVM);
+    verifyDistributedLockServiceMXBean(this.managerVM, 0);
   }
 
-  public void ensureProxyCleanup(final VM vm) {
-
-    SerializableRunnable ensureProxyCleanup = new SerializableRunnable("Ensure Proxy cleanup") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Set<DistributedMember> otherMemberSet =
-            cache.getDistributionManager().getOtherNormalDistributionManagerIds();
-        final SystemManagementService service = (SystemManagementService) getManagementService();
-
-
-        for (final DistributedMember member : otherMemberSet) {
-          RegionMXBean bean = null;
-          try {
-
-            Wait.waitForCriterion(new WaitCriterion() {
-
-              LockServiceMXBean bean = null;
-
-              public String description() {
-                return "Waiting for the proxy to get deleted at managing node";
-              }
-
-              public boolean done() {
-                ObjectName objectName = service.getRegionMBeanName(member, LOCK_SERVICE_NAME);
-                bean = service.getMBeanProxy(objectName, LockServiceMXBean.class);
-                boolean done = (bean == null);
-                return done;
-              }
-
-            }, MAX_WAIT, 500, true);
-
-          } catch (Exception e) {
-            throw new AssertionError("could not remove proxies in required time", e);
-
-          }
-          assertNull(bean);
-
-        }
+  private void verifyProxyCleanupInManager(final VM managerVM) {
+    managerVM.invoke("verifyProxyCleanupInManager", () -> {
+      Set<DistributedMember> otherMembers = this.managementTestRule.getOtherNormalMembers();
+      SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
+      for (final DistributedMember member : otherMembers) {
+        ObjectName objectName = service.getRegionMBeanName(member, LOCK_SERVICE_NAME);
+        await().until(
+            () -> assertThat(service.getMBeanProxy(objectName, LockServiceMXBean.class)).isNull());
       }
-    };
-    vm.invoke(ensureProxyCleanup);
+    });
   }
 
-  /**
-   * Creates a grantor lock service
-   * 
-   * @param vm
-   */
-  @SuppressWarnings("serial")
-  protected void createGrantorLockService(final VM vm) {
-    SerializableRunnable createGrantorLockService =
-        new SerializableRunnable("Create Grantor LockService") {
-          public void run() {
-            GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-            assertNull(DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME));
+  private void createLockServiceGrantor(final VM memberVM) {
+    memberVM.invoke("createLockServiceGrantor", () -> {
+      assertThat(DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME)).isNull();
 
-            DLockService service = (DLockService) DistributedLockService.create(LOCK_SERVICE_NAME,
-                cache.getDistributedSystem());
+      DLockService lockService = (DLockService) DistributedLockService.create(LOCK_SERVICE_NAME,
+          this.managementTestRule.getCache().getDistributedSystem());
+      DistributedMember grantor = lockService.getLockGrantorId().getLockGrantorMember();
+      assertThat(grantor).isNotNull();
 
-            assertSame(service, DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME));
+      LockServiceMXBean lockServiceMXBean = awaitLockServiceMXBean(LOCK_SERVICE_NAME);
 
-            InternalDistributedMember grantor = service.getLockGrantorId().getLockGrantorMember();
-
-            assertNotNull(grantor);
+      assertThat(lockServiceMXBean).isNotNull();
+      assertThat(lockServiceMXBean.isDistributed()).isTrue();
+      assertThat(lockServiceMXBean.getName()).isEqualTo(LOCK_SERVICE_NAME);
+      assertThat(lockServiceMXBean.isLockGrantor()).isTrue();
+      assertThat(lockServiceMXBean.fetchGrantorMember())
+          .isEqualTo(this.managementTestRule.getDistributedMember().getId());
+    });
+  }
 
-            LogWriterUtils.getLogWriter().info("In identifyLockGrantor - grantor is " + grantor);
+  private void createLockService(final VM anyVM) {
+    anyVM.invoke("createLockService", () -> {
+      assertThat(DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME)).isNull();
 
+      DistributedLockService.create(LOCK_SERVICE_NAME,
+          this.managementTestRule.getCache().getDistributedSystem());
 
+      LockServiceMXBean lockServiceMXBean = awaitLockServiceMXBean(LOCK_SERVICE_NAME);
 
-            ManagementService mgmtService = getManagementService();
+      assertThat(lockServiceMXBean).isNotNull();
+      assertThat(lockServiceMXBean.isDistributed()).isTrue();
+      assertThat(lockServiceMXBean.isLockGrantor()).isFalse();
+    });
+  }
 
-            LockServiceMXBean bean = mgmtService.getLocalLockServiceMBean(LOCK_SERVICE_NAME);
+  private void closeLockService(final VM anyVM) {
+    anyVM.invoke("closeLockService", () -> {
+      assertThat(DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME)).isNotNull();
+      DistributedLockService.destroy(LOCK_SERVICE_NAME);
 
-            assertNotNull(bean);
+      awaitLockServiceMXBeanIsNull(LOCK_SERVICE_NAME);
 
-            assertTrue(bean.isDistributed());
+      ManagementService service = this.managementTestRule.getManagementService();
+      LockServiceMXBean lockServiceMXBean = service.getLocalLockServiceMBean(LOCK_SERVICE_NAME);
+      assertThat(lockServiceMXBean).isNull();
+    });
+  }
 
-            assertEquals(bean.getName(), LOCK_SERVICE_NAME);
+  private void verifyLockServiceMXBeanInMember(final VM memberVM) {
+    memberVM.invoke("verifyLockServiceMXBeanInManager", () -> {
+      DistributedLockService lockService =
+          DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME);
+      lockService.lock("lockObject_" + identifyPid(), MAX_WAIT_MILLIS, -1);
 
-            assertTrue(bean.isLockGrantor());
+      ManagementService service = this.managementTestRule.getManagementService();
+      LockServiceMXBean lockServiceMXBean = service.getLocalLockServiceMBean(LOCK_SERVICE_NAME);
+      assertThat(lockServiceMXBean).isNotNull();
 
-            assertEquals(cache.getDistributedSystem().getMemberId(), bean.fetchGrantorMember());
+      String[] listHeldLock = lockServiceMXBean.listHeldLocks();
+      assertThat(listHeldLock).hasSize(1);
 
-          }
-        };
-    vm.invoke(createGrantorLockService);
+      Map<String, String> lockThreadMap = lockServiceMXBean.listThreadsHoldingLock();
+      assertThat(lockThreadMap).hasSize(1);
+    });
   }
 
   /**
-   * Creates a named lock service
-   * 
-   * @param vm
+   * Verify lock data from remote Managing node
    */
-  @SuppressWarnings("serial")
-  protected void createLockService(final VM vm) {
-    SerializableRunnable createLockService = new SerializableRunnable("Create LockService") {
-      public void run() {
-        assertNull(DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME));
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        DistributedLockService service =
-            DistributedLockService.create(LOCK_SERVICE_NAME, cache.getDistributedSystem());
-
-        assertSame(service, DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME));
-
+  private void verifyLockServiceMXBeanInManager(final VM managerVM) throws Exception {
+    managerVM.invoke("verifyLockServiceMXBeanInManager", () -> {
+      Set<DistributedMember> otherMembers = this.managementTestRule.getOtherNormalMembers();
 
+      for (DistributedMember member : otherMembers) {
+        LockServiceMXBean lockServiceMXBean =
+            awaitLockServiceMXBeanProxy(member, LOCK_SERVICE_NAME);
+        assertThat(lockServiceMXBean).isNotNull();
 
-        ManagementService mgmtService = getManagementService();
+        String[] listHeldLock = lockServiceMXBean.listHeldLocks();
+        assertThat(listHeldLock).hasSize(1);
 
-        LockServiceMXBean bean = mgmtService.getLocalLockServiceMBean(LOCK_SERVICE_NAME);
-
-        assertNotNull(bean);
-
-        assertTrue(bean.isDistributed());
-
-        assertFalse(bean.isLockGrantor());
+        Map<String, String> lockThreadMap = lockServiceMXBean.listThreadsHoldingLock();
+        assertThat(lockThreadMap).hasSize(1);
       }
-    };
-    vm.invoke(createLockService);
+    });
+  }
+
+  private void verifyFetchOperations(final VM memberVM, final DistributedMember member) {
+    memberVM.invoke("verifyFetchOperations", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+
+      DistributedSystemMXBean distributedSystemMXBean = awaitDistributedSystemMXBean();
+      ObjectName distributedLockServiceMXBeanName =
+          MBeanJMXAdapter.getDistributedLockServiceName(LOCK_SERVICE_NAME);
+      assertThat(distributedSystemMXBean.fetchDistributedLockServiceObjectName(LOCK_SERVICE_NAME))
+          .isEqualTo(distributedLockServiceMXBeanName);
+
+      ObjectName lockServiceMXBeanName =
+          MBeanJMXAdapter.getLockServiceMBeanName(member.getId(), LOCK_SERVICE_NAME);
+      assertThat(
+          distributedSystemMXBean.fetchLockServiceObjectName(member.getId(), LOCK_SERVICE_NAME))
+              .isEqualTo(lockServiceMXBeanName);
+    });
   }
 
   /**
-   * Closes a named lock service
-   * 
-   * @param vm
+   * Verify Aggregate MBean
    */
-  @SuppressWarnings("serial")
-  protected void closeLockService(final VM vm) {
-    SerializableRunnable closeLockService = new SerializableRunnable("Close LockService") {
-      public void run() {
-
-        DistributedLockService service = DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME);
-
-        DistributedLockService.destroy(LOCK_SERVICE_NAME);
-
-        ManagementService mgmtService = getManagementService();
-
-        LockServiceMXBean bean = null;
-        try {
+  private void verifyDistributedLockServiceMXBean(final VM managerVM, final int memberCount) {
+    managerVM.invoke("verifyDistributedLockServiceMXBean", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+
+      if (memberCount == 0) {
+        await().until(
+            () -> assertThat(service.getDistributedLockServiceMXBean(LOCK_SERVICE_NAME)).isNull());
+        return;
+      }
 
-          bean = mgmtService.getLocalLockServiceMBean(LOCK_SERVICE_NAME);
+      DistributedLockServiceMXBean distributedLockServiceMXBean =
+          awaitDistributedLockServiceMXBean(LOCK_SERVICE_NAME, memberCount);
+      assertThat(distributedLockServiceMXBean).isNotNull();
+      assertThat(distributedLockServiceMXBean.getName()).isEqualTo(LOCK_SERVICE_NAME);
+    });
+  }
 
-        } catch (ManagementException mgs) {
+  private DistributedSystemMXBean awaitDistributedSystemMXBean() {
+    ManagementService service = this.managementTestRule.getManagementService();
 
-        }
-        assertNull(bean);
+    await().until(() -> assertThat(service.getDistributedSystemMXBean()).isNotNull());
 
-      }
-    };
-    vm.invoke(closeLockService);
+    return service.getDistributedSystemMXBean();
   }
 
   /**
-   * Lock data related verifications
-   * 
-   * @param vm
+   * Await and return a DistributedRegionMXBean proxy with specified member count.
    */
-  @SuppressWarnings("serial")
-  protected void verifyLockData(final VM vm) {
-    SerializableRunnable verifyLockData = new SerializableRunnable("Verify LockService") {
-      public void run() {
-
-        DistributedLockService service = DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME);
-
-        final String LOCK_OBJECT = "lockObject_" + vm.getPid();
-
-        Wait.waitForCriterion(new WaitCriterion() {
-          DistributedLockService service = null;
-
-          public String description() {
-            return "Waiting for the lock service to be initialised";
-          }
-
-          public boolean done() {
-            DistributedLockService service =
-                DistributedLockService.getServiceNamed(LOCK_SERVICE_NAME);
-            boolean done = service != null;
-            return done;
-          }
-
-        }, MAX_WAIT, 500, true);
-
-        service.lock(LOCK_OBJECT, 1000, -1);
-
+  private DistributedLockServiceMXBean awaitDistributedLockServiceMXBean(
+      final String lockServiceName, final int memberCount) {
+    ManagementService service = this.managementTestRule.getManagementService();
 
-        ManagementService mgmtService = getManagementService();
+    await().until(() -> {
+      assertThat(service.getDistributedLockServiceMXBean(lockServiceName)).isNotNull();
+      assertThat(service.getDistributedLockServiceMXBean(lockServiceName).getMemberCount())
+          .isEqualTo(memberCount);
+    });
 
-        LockServiceMXBean bean = null;
-        try {
-
-          bean = mgmtService.getLocalLockServiceMBean(LOCK_SERVICE_NAME);
-
-        } catch (ManagementException mgs) {
-
-        }
-        assertNotNull(bean);
-        String[] listHeldLock = bean.listHeldLocks();
-        assertEquals(listHeldLock.length, 1);
-        LogWriterUtils.getLogWriter().info("List Of Lock Object is  " + listHeldLock[0]);
-        Map<String, String> lockThreadMap = bean.listThreadsHoldingLock();
-        assertEquals(lockThreadMap.size(), 1);
-        LogWriterUtils.getLogWriter().info("List Of Lock Thread is  " + lockThreadMap.toString());
-      }
-    };
-    vm.invoke(verifyLockData);
+    return service.getDistributedLockServiceMXBean(lockServiceName);
   }
 
   /**
-   * Verify lock data from remote Managing node
-   * 
-   * @param vm
+   * Await and return a LockServiceMXBean proxy for a specific member and lockServiceName.
    */
-  @SuppressWarnings("serial")
-  protected void verifyLockDataRemote(final VM vm) {
-    SerializableRunnable verifyLockDataRemote =
-        new SerializableRunnable("Verify LockService Remote") {
-          public void run() {
-
-            GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-            Set<DistributedMember> otherMemberSet =
-                cache.getDistributionManager().getOtherNormalDistributionManagerIds();
-
-            for (DistributedMember member : otherMemberSet) {
-              LockServiceMXBean bean = null;
-              try {
-                bean = MBeanUtil.getLockServiceMbeanProxy(member, LOCK_SERVICE_NAME);
-              } catch (Exception e) {
-                InternalDistributedSystem.getLoggerI18n()
-                    .fine("Undesired Result , LockServiceMBean Should not be null", e);
-
-              }
-              assertNotNull(bean);
-              String[] listHeldLock = bean.listHeldLocks();
-              assertEquals(listHeldLock.length, 1);
-              LogWriterUtils.getLogWriter().info("List Of Lock Object is  " + listHeldLock[0]);
-              Map<String, String> lockThreadMap = bean.listThreadsHoldingLock();
-              assertEquals(lockThreadMap.size(), 1);
-              LogWriterUtils.getLogWriter()
-                  .info("List Of Lock Thread is  " + lockThreadMap.toString());
-            }
-
-          }
-        };
-    vm.invoke(verifyLockDataRemote);
-  }
+  private LockServiceMXBean awaitLockServiceMXBeanProxy(final DistributedMember member,
+      final String lockServiceName) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    ObjectName lockServiceMXBeanName = service.getLockServiceMBeanName(member, lockServiceName);
 
-  protected void checkNavigation(final VM vm, final DistributedMember lockServiceMember) {
-    SerializableRunnable checkNavigation = new SerializableRunnable("Check Navigation") {
-      public void run() {
-
-        final ManagementService service = getManagementService();
-
-        DistributedSystemMXBean disMBean = service.getDistributedSystemMXBean();
-        try {
-          ObjectName expected = MBeanJMXAdapter.getDistributedLockServiceName(LOCK_SERVICE_NAME);
-          ObjectName actual = disMBean.fetchDistributedLockServiceObjectName(LOCK_SERVICE_NAME);
-          assertEquals(expected, actual);
-        } catch (Exception e) {
-          throw new AssertionError("Lock Service Navigation Failed ", e);
-        }
-
-        try {
-          ObjectName expected =
-              MBeanJMXAdapter.getLockServiceMBeanName(lockServiceMember.getId(), LOCK_SERVICE_NAME);
-          ObjectName actual =
-              disMBean.fetchLockServiceObjectName(lockServiceMember.getId(), LOCK_SERVICE_NAME);
-          assertEquals(expected, actual);
-        } catch (Exception e) {
-          throw new AssertionError("Lock Service Navigation Failed ", e);
-        }
+    await().until(
+        () -> assertThat(service.getMBeanProxy(lockServiceMXBeanName, LockServiceMXBean.class))
+            .isNotNull());
 
-      }
-    };
-    vm.invoke(checkNavigation);
+    return service.getMBeanProxy(lockServiceMXBeanName, LockServiceMXBean.class);
   }
 
   /**
-   * Verify Aggregate MBean
-   * 
-   * @param vm
+   * Await creation of local LockServiceMXBean for specified lockServiceName.
    */
-  @SuppressWarnings("serial")
-  protected void checkAggregate(final VM vm, final int expectedMembers) {
-    SerializableRunnable checkAggregate = new SerializableRunnable("Verify Aggregate MBean") {
-      public void run() {
-
-        final ManagementService service = getManagementService();
-        if (expectedMembers == 0) {
-          try {
-            Wait.waitForCriterion(new WaitCriterion() {
-
-              DistributedLockServiceMXBean bean = null;
+  private LockServiceMXBean awaitLockServiceMXBean(final String lockServiceName) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
-              public String description() {
-                return "Waiting for the proxy to get deleted at managing node";
-              }
+    await().until(() -> assertThat(service.getLocalLockServiceMBean(lockServiceName)).isNotNull());
 
-              public boolean done() {
-                bean = service.getDistributedLockServiceMXBean(LOCK_SERVICE_NAME);
-
-                boolean done = (bean == null);
-                return done;
-              }
-
-            }, MAX_WAIT, 500, true);
-
-          } catch (Exception e) {
-            throw new AssertionError("could not remove Aggregate Bean in required time", e);
-
-          }
-          return;
-        }
+    return service.getLocalLockServiceMBean(lockServiceName);
+  }
 
-        DistributedLockServiceMXBean bean = null;
-        try {
-          bean = MBeanUtil.getDistributedLockMbean(LOCK_SERVICE_NAME, expectedMembers);
-        } catch (Exception e) {
-          InternalDistributedSystem.getLoggerI18n()
-              .fine("Undesired Result , LockServiceMBean Should not be null", e);
+  /**
+   * Await destruction of local LockServiceMXBean for specified lockServiceName.
+   */
+  private void awaitLockServiceMXBeanIsNull(final String lockServiceName) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
-        }
-        assertNotNull(bean);
-        assertEquals(bean.getName(), LOCK_SERVICE_NAME);
+    await().until(() -> assertThat(service.getLocalLockServiceMBean(lockServiceName)).isNull());
+  }
 
-      }
-    };
-    vm.invoke(checkAggregate);
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(MAX_WAIT_MILLIS, MILLISECONDS);
   }
 }
+


[6/8] geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/DiskManagementDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/DiskManagementDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/DiskManagementDUnitTest.java
index bcfadde..50533d3 100644
--- a/geode-core/src/test/java/org/apache/geode/management/DiskManagementDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/DiskManagementDUnitTest.java
@@ -14,24 +14,25 @@
  */
 package org.apache.geode.management;
 
-import org.junit.experimental.categories.Category;
-import org.junit.Test;
-
-import static org.junit.Assert.*;
-
-import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
+import static java.util.concurrent.TimeUnit.*;
+import static org.assertj.core.api.Assertions.*;
 
 import java.io.File;
-import java.util.Arrays;
-import java.util.List;
+import java.io.Serializable;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeoutException;
 
 import javax.management.ObjectName;
 
-import org.apache.geode.LogWriter;
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
 import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.DataPolicy;
 import org.apache.geode.cache.DiskStore;
@@ -40,674 +41,366 @@ import org.apache.geode.cache.Region;
 import org.apache.geode.cache.RegionFactory;
 import org.apache.geode.cache.Scope;
 import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.DiskRegion;
 import org.apache.geode.internal.cache.DiskRegionStats;
 import org.apache.geode.internal.cache.DistributedRegion;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.cache.LocalRegion;
 import org.apache.geode.internal.cache.persistence.PersistentMemberID;
 import org.apache.geode.internal.cache.persistence.PersistentMemberManager;
-import org.apache.geode.management.internal.MBeanJMXAdapter;
+import org.apache.geode.internal.process.ProcessUtils;
+import org.apache.geode.management.internal.SystemManagementService;
 import org.apache.geode.test.dunit.AsyncInvocation;
-import org.apache.geode.test.dunit.SerializableCallable;
-import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
 
 /**
  * Test cases to cover all test cases which pertains to disk from Management layer
- * 
- * 
  */
 @Category(DistributedTest.class)
-public class DiskManagementDUnitTest extends ManagementTestBase {
-
-  /**
-   * 
-   */
-  private static final long serialVersionUID = 1L;
-
-  // This must be bigger than the dunit ack-wait-threshold for the revoke
-  // tests. The command line is setting the ack-wait-threshold to be
-  // 60 seconds.
-  private static final int MAX_WAIT = 70 * 1000;
-
-  boolean testFailed = false;
+@SuppressWarnings({"serial", "unused"})
+public class DiskManagementDUnitTest implements Serializable {
 
-  String failureCause = "";
-  static final String REGION_NAME = "region";
+  private static final String REGION_NAME =
+      DiskManagementDUnitTest.class.getSimpleName() + "_region";
 
   private File diskDir;
 
-  protected static LogWriter logWriter;
+  @Manager
+  private VM managerVM;
 
-  public DiskManagementDUnitTest() throws Exception {
-    super();
+  @Member
+  private VM[] memberVMs;
 
-    diskDir = new File("diskDir-" + getName()).getAbsoluteFile();
-    org.apache.geode.internal.FileUtil.delete(diskDir);
-    diskDir.mkdir();
-    diskDir.deleteOnExit();
-  }
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().start(true).build();
 
-  @Override
-  protected final void postSetUpManagementTestBase() throws Exception {
-    failureCause = "";
-    testFailed = false;
-  }
+  @Rule
+  public SerializableTemporaryFolder temporaryFolder = new SerializableTemporaryFolder();
 
-  @Override
-  protected final void postTearDownManagementTestBase() throws Exception {
-    org.apache.geode.internal.FileUtil.delete(diskDir);
+  @Before
+  public void before() throws Exception {
+    this.diskDir = this.temporaryFolder.newFolder("diskDir");
   }
 
   /**
-   * Tests Disk Compaction from a MemberMbean which is at cache level. All the disks which belong to
-   * the cache should be compacted.
-   * 
-   * @throws Exception
+   * Tests Disk Compaction from a MemberMXBean which is at cache level. All the disks which belong
+   * to the cache should be compacted.
    */
-
   @Test
-  public void testDiskCompact() throws Throwable {
-    initManagement(false);
-    for (VM vm : getManagedNodeList()) {
-      createPersistentRegion(vm);
-      makeDiskCompactable(vm);
+  public void testDiskCompact() throws Exception {
+    for (VM memberVM : this.memberVMs) {
+      createPersistentRegion(memberVM);
+      makeDiskCompactable(memberVM);
     }
 
-    for (VM vm : getManagedNodeList()) {
-      compactAllDiskStores(vm);
+    for (VM memberVM : this.memberVMs) {
+      compactAllDiskStores(memberVM);
     }
-
   }
 
   /**
-   * Tests Disk Compaction from a MemberMbean which is at cache level. All the disks which belong to
-   * the cache should be compacted.
-   * 
-   * @throws Exception
+   * Tests Disk Compaction from a MemberMXBean which is at cache level. All the disks which belong
+   * to the cache should be compacted.
    */
-
   @Test
-  public void testDiskCompactRemote() throws Throwable {
-
-    initManagement(false);
-    for (VM vm : getManagedNodeList()) {
-      createPersistentRegion(vm);
-      makeDiskCompactable(vm);
+  public void testDiskCompactRemote() throws Exception {
+    for (VM memberVM : this.memberVMs) {
+      createPersistentRegion(memberVM);
+      makeDiskCompactable(memberVM);
     }
-    compactDiskStoresRemote(managingNode);
 
+    compactDiskStoresRemote(this.managerVM, this.memberVMs.length);
   }
 
   /**
    * Tests various operations defined on DiskStore Mbean
-   * 
-   * @throws Exception
    */
-
   @Test
-  public void testDiskOps() throws Throwable {
-
-    initManagement(false);
-    for (VM vm : getManagedNodeList()) {
-      createPersistentRegion(vm);
-      makeDiskCompactable(vm);
-      invokeFlush(vm);
-      invokeForceRoll(vm);
-      invokeForceCompaction(vm);
+  public void testDiskOps() throws Exception {
+    for (VM memberVM : this.memberVMs) {
+      createPersistentRegion(memberVM);
+      makeDiskCompactable(memberVM);
+      invokeFlush(memberVM);
+      invokeForceRoll(memberVM);
+      invokeForceCompaction(memberVM);
     }
-
   }
 
   @Test
-  public void testDiskBackupAllMembers() throws Throwable {
-    initManagement(false);
-    for (VM vm : getManagedNodeList()) {
-      createPersistentRegion(vm);
-      makeDiskCompactable(vm);
-
+  public void testDiskBackupAllMembers() throws Exception {
+    for (VM memberVM : this.memberVMs) {
+      createPersistentRegion(memberVM);
+      makeDiskCompactable(memberVM);
     }
-    backupAllMembers(managingNode);
+
+    backupAllMembers(this.managerVM, this.memberVMs.length);
   }
 
   /**
-   * Checks the test case of missing disks and revoking them through MemberMbean interfaces
-   * 
-   * @throws Throwable
+   * Checks the test case of missing disks and revoking them through MemberMXBean interfaces
    */
-  @SuppressWarnings("serial")
   @Test
-  public void testMissingMembers() throws Throwable {
+  public void testMissingMembers() throws Exception {
+    VM memberVM1 = this.memberVMs[0];
+    VM memberVM2 = this.memberVMs[1];
 
-    initManagement(false);
-    VM vm0 = getManagedNodeList().get(0);
-    VM vm1 = getManagedNodeList().get(1);
-    VM vm2 = getManagedNodeList().get(2);
+    createPersistentRegion(memberVM1);
+    createPersistentRegion(memberVM2);
 
-    org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Creating region in VM0");
-    createPersistentRegion(vm0);
-    org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Creating region in VM1");
-    createPersistentRegion(vm1);
+    putAnEntry(memberVM1);
 
-    putAnEntry(vm0);
+    this.managerVM.invoke("checkForMissingDiskStores", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+      PersistentMemberDetails[] missingDiskStores = distributedSystemMXBean.listMissingDiskStores();
 
+      assertThat(missingDiskStores).isNull();
+    });
 
-    managingNode.invoke(new SerializableRunnable("Check for waiting regions") {
+    closeRegion(memberVM1);
 
-      public void run() {
-        Cache cache = getCache();
-        ManagementService service = getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        PersistentMemberDetails[] missingDiskStores = bean.listMissingDiskStores();
+    updateTheEntry(memberVM2, "C");
 
-        assertNull(missingDiskStores);
-      }
-    });
+    closeRegion(memberVM2);
 
-    org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("closing region in vm0");
-    closeRegion(vm0);
-
-    updateTheEntry(vm1);
-
-    org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("closing region in vm1");
-    closeRegion(vm1);
-    AsyncInvocation future = createPersistentRegionAsync(vm0);
-    waitForBlockedInitialization(vm0);
-    assertTrue(future.isAlive());
-
-    managingNode.invoke(new SerializableRunnable("Revoke the member") {
-
-      public void run() {
-        Cache cache = getCache();
-        GemFireCacheImpl cacheImpl = (GemFireCacheImpl) cache;
-        ManagementService service = getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        PersistentMemberDetails[] missingDiskStores = bean.listMissingDiskStores();
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter()
-            .info("waiting members=" + missingDiskStores);
-        assertNotNull(missingDiskStores);
-        assertEquals(1, missingDiskStores.length);
-
-        for (PersistentMemberDetails id : missingDiskStores) {
-          org.apache.geode.test.dunit.LogWriterUtils.getLogWriter()
-              .info("Missing DiskStoreID is =" + id.getDiskStoreId());
-          org.apache.geode.test.dunit.LogWriterUtils.getLogWriter()
-              .info("Missing Host is =" + id.getHost());
-          org.apache.geode.test.dunit.LogWriterUtils.getLogWriter()
-              .info("Missing Directory is =" + id.getDirectory());
-
-          try {
-            bean.revokeMissingDiskStores(id.getDiskStoreId());
-          } catch (Exception e) {
-            fail("revokeMissingDiskStores failed with exception " + e);
-          }
-        }
-      }
-    });
+    AsyncInvocation creatingPersistentRegionAsync = createPersistentRegionAsync(memberVM1);
 
-    future.join(MAX_WAIT);
-    if (future.isAlive()) {
-      fail("Region not created within" + MAX_WAIT);
-    }
-    if (future.exceptionOccurred()) {
-      throw new Exception(future.getException());
-    }
-    checkForRecoveryStat(vm0, true);
-    // Check to make sure we recovered the old
-    // value of the entry.
-    SerializableRunnable checkForEntry = new SerializableRunnable("check for the entry") {
-
-      public void run() {
-        Cache cache = getCache();
-        Region region = cache.getRegion(REGION_NAME);
-        assertEquals("B", region.get("A"));
-      }
-    };
-    vm0.invoke(checkForEntry);
+    memberVM1.invoke(() -> await().until(() -> {
+      GemFireCacheImpl cache = (GemFireCacheImpl) this.managementTestRule.getCache();
+      PersistentMemberManager persistentMemberManager = cache.getPersistentMemberManager();
+      Map<String, Set<PersistentMemberID>> regions = persistentMemberManager.getWaitingRegions();
+      return !regions.isEmpty();
+    }));
 
-  }
+    assertThat(creatingPersistentRegionAsync.isAlive()).isTrue();
 
-  protected void checkNavigation(final VM vm, final DistributedMember diskMember,
-      final String diskStoreName) {
-    SerializableRunnable checkNavigation = new SerializableRunnable("Check Navigation") {
-      public void run() {
+    this.managerVM.invoke("revokeMissingDiskStore", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
+      PersistentMemberDetails[] missingDiskStores = bean.listMissingDiskStores();
 
-        final ManagementService service = getManagementService();
+      assertThat(missingDiskStores).isNotNull().hasSize(1);
 
-        DistributedSystemMXBean disMBean = service.getDistributedSystemMXBean();
-        try {
-          ObjectName expected =
-              MBeanJMXAdapter.getDiskStoreMBeanName(diskMember.getId(), diskStoreName);
-          ObjectName actual = disMBean.fetchDiskStoreObjectName(diskMember.getId(), diskStoreName);
-          assertEquals(expected, actual);
-        } catch (Exception e) {
-          fail("Disk Store Navigation Failed " + e);
-        }
+      assertThat(bean.revokeMissingDiskStores(missingDiskStores[0].getDiskStoreId())).isTrue();
+    });
 
+    await(creatingPersistentRegionAsync);
 
-      }
-    };
-    vm.invoke(checkNavigation);
-  }
+    verifyRecoveryStats(memberVM1, true);
 
-  /**
-   * get Distributed member for a given vm
-   */
-  @SuppressWarnings("serial")
-  protected static DistributedMember getMember() throws Exception {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    return cache.getDistributedSystem().getDistributedMember();
+    // Check to make sure we recovered the old value of the entry.
+    memberVM1.invoke("check for the entry", () -> {
+      Cache cache = this.managementTestRule.getCache();
+      Region region = cache.getRegion(REGION_NAME);
+      assertThat(region.get("A")).isEqualTo("B");
+    });
   }
 
   /**
    * Invokes flush on the given disk store by MBean interface
-   * 
-   * @param vm reference to VM
    */
-  @SuppressWarnings("serial")
-  public void invokeFlush(final VM vm) {
-    SerializableRunnable invokeFlush = new SerializableRunnable("Invoke Flush On Disk") {
-      public void run() {
-        Cache cache = getCache();
-        DiskStoreFactory dsf = cache.createDiskStoreFactory();
-        String name = "testFlush_" + vm.getPid();
-        DiskStore ds = dsf.create(name);
-
-        ManagementService service = getManagementService();
-        DiskStoreMXBean bean = service.getLocalDiskStoreMBean(name);
-        assertNotNull(bean);
-        bean.flush();
-      }
-    };
-    vm.invoke(invokeFlush);
+  private void invokeFlush(final VM memberVM) {
+    memberVM.invoke("invokeFlush", () -> {
+      Cache cache = this.managementTestRule.getCache();
+      DiskStoreFactory diskStoreFactory = cache.createDiskStoreFactory();
+      String name = "testFlush_" + ProcessUtils.identifyPid();
+      DiskStore diskStore = diskStoreFactory.create(name);
+
+      ManagementService service = this.managementTestRule.getManagementService();
+      DiskStoreMXBean diskStoreMXBean = service.getLocalDiskStoreMBean(name);
+      assertThat(diskStoreMXBean).isNotNull();
+      assertThat(diskStoreMXBean.getName()).isEqualTo(diskStore.getName());
+
+      diskStoreMXBean.flush();
+    });
   }
 
   /**
    * Invokes force roll on disk store by MBean interface
-   * 
-   * @param vm reference to VM
    */
-  @SuppressWarnings("serial")
-  public void invokeForceRoll(final VM vm) {
-    SerializableRunnable invokeForceRoll = new SerializableRunnable("Invoke Force Roll") {
-      public void run() {
-        Cache cache = getCache();
-        DiskStoreFactory dsf = cache.createDiskStoreFactory();
-        String name = "testForceRoll_" + vm.getPid();
-        DiskStore ds = dsf.create(name);
-        ManagementService service = getManagementService();
-        DiskStoreMXBean bean = service.getLocalDiskStoreMBean(name);
-        assertNotNull(bean);
-        bean.forceRoll();
-      }
-    };
-    vm.invoke(invokeForceRoll);
+  private void invokeForceRoll(final VM memberVM) {
+    memberVM.invoke("invokeForceRoll", () -> {
+      Cache cache = this.managementTestRule.getCache();
+      DiskStoreFactory diskStoreFactory = cache.createDiskStoreFactory();
+      String name = "testForceRoll_" + ProcessUtils.identifyPid();
+      DiskStore diskStore = diskStoreFactory.create(name);
+
+      ManagementService service = this.managementTestRule.getManagementService();
+      DiskStoreMXBean diskStoreMXBean = service.getLocalDiskStoreMBean(name);
+      assertThat(diskStoreMXBean).isNotNull();
+      assertThat(diskStoreMXBean.getName()).isEqualTo(diskStore.getName());
+
+      diskStoreMXBean.forceRoll();
+    });
   }
 
   /**
    * Invokes force compaction on disk store by MBean interface
-   * 
-   * @param vm reference to VM
    */
-  @SuppressWarnings("serial")
-  public void invokeForceCompaction(final VM vm) {
-    SerializableRunnable invokeForceCompaction =
-        new SerializableRunnable("Invoke Force Compaction") {
-          public void run() {
-            Cache cache = getCache();
-            DiskStoreFactory dsf = cache.createDiskStoreFactory();
-            dsf.setAllowForceCompaction(true);
-            String name = "testForceCompaction_" + vm.getPid();
-            DiskStore ds = dsf.create(name);
-            ManagementService service = getManagementService();
-            DiskStoreMXBean bean = service.getLocalDiskStoreMBean(name);
-            assertNotNull(bean);
-            assertEquals(false, bean.forceCompaction());
-          }
-        };
-    vm.invoke(invokeForceCompaction);
+  private void invokeForceCompaction(final VM memberVM) {
+    memberVM.invoke("invokeForceCompaction", () -> {
+      Cache cache = this.managementTestRule.getCache();
+      DiskStoreFactory dsf = cache.createDiskStoreFactory();
+      dsf.setAllowForceCompaction(true);
+      String name = "testForceCompaction_" + ProcessUtils.identifyPid();
+      DiskStore diskStore = dsf.create(name);
+
+      ManagementService service = this.managementTestRule.getManagementService();
+      DiskStoreMXBean diskStoreMXBean = service.getLocalDiskStoreMBean(name);
+      assertThat(diskStoreMXBean).isNotNull();
+      assertThat(diskStoreMXBean.getName()).isEqualTo(diskStore.getName());
+
+      assertThat(diskStoreMXBean.forceCompaction()).isFalse();
+    });
   }
 
   /**
    * Makes the disk compactable by adding and deleting some entries
-   * 
-   * @throws Exception
    */
-  @SuppressWarnings("serial")
-  public void makeDiskCompactable(VM vm1) throws Exception {
-    vm1.invoke(new SerializableRunnable("Make The Disk Compactable") {
-
-      public void run() {
-        Cache cache = getCache();
-        Region region = cache.getRegion(REGION_NAME);
-        DiskRegion dr = ((LocalRegion) region).getDiskRegion();
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("putting key1");
-        region.put("key1", "value1");
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("putting key2");
-        region.put("key2", "value2");
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("removing key2");
-        region.remove("key2");
-        // now that it is compactable the following forceCompaction should
-        // go ahead and do a roll and compact it.
-      }
+  private void makeDiskCompactable(final VM memberVM) throws Exception {
+    memberVM.invoke("makeDiskCompactable", () -> {
+      Cache cache = this.managementTestRule.getCache();
+      Region region = cache.getRegion(REGION_NAME);
+      region.put("key1", "value1");
+      region.put("key2", "value2");
+      region.remove("key2");
+      // now that it is compactable the following forceCompaction should
+      // go ahead and do a roll and compact it.
     });
-
   }
 
-
-
   /**
    * Compacts all DiskStores belonging to a member
-   * 
-   * @param vm1 reference to VM
-   * @throws Exception
    */
-  @SuppressWarnings("serial")
-  public void compactAllDiskStores(VM vm1) throws Exception {
-
-    vm1.invoke(new SerializableCallable("Compact All Disk Stores") {
-
-      public Object call() throws Exception {
-        ManagementService service = getManagementService();
-        MemberMXBean memberBean = service.getMemberMXBean();
-        String[] compactedDiskStores = memberBean.compactAllDiskStores();
-
-        assertTrue(compactedDiskStores.length > 0);
-        for (int i = 0; i < compactedDiskStores.length; i++) {
-          org.apache.geode.test.dunit.LogWriterUtils.getLogWriter()
-              .info("<ExpectedString> Compacted Store " + i + " " + compactedDiskStores[i]
-                  + "</ExpectedString> ");
-        }
-
-        return null;
-      }
+  private void compactAllDiskStores(final VM memberVM) throws Exception {
+    memberVM.invoke("compactAllDiskStores", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      MemberMXBean memberMXBean = service.getMemberMXBean();
+      String[] compactedDiskStores = memberMXBean.compactAllDiskStores();
+      assertThat(compactedDiskStores).hasSize(1);
     });
-
   }
 
   /**
    * Takes a back up of all the disk store in a given directory
    */
-  @SuppressWarnings("serial")
-  public void backupAllMembers(final VM managingVM) throws Exception {
+  private void backupAllMembers(final VM managerVM, final int memberCount) {
+    managerVM.invoke("backupAllMembers", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
+      File backupDir = this.temporaryFolder.newFolder("backupDir");
 
-    managingVM.invoke(new SerializableCallable("Backup All Disk Stores") {
+      DiskBackupStatus status = bean.backupAllMembers(backupDir.getAbsolutePath(), null);
 
-      public Object call() throws Exception {
-        ManagementService service = getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        DiskBackupStatus status =
-            bean.backupAllMembers(getBackupDir("test_backupAllMembers").getAbsolutePath(), null);
-
-        return null;
-      }
+      assertThat(status.getBackedUpDiskStores().keySet().size()).isEqualTo(memberCount);
+      assertThat(status.getOfflineDiskStores()).isEqualTo(null); // TODO: fix GEODE-1946
     });
-
   }
 
   /**
-   * Compact a disk store from Managing node
+   * Compact a disk store from managerVM VM
    */
-  @SuppressWarnings("serial")
-  public void compactDiskStoresRemote(VM managingVM) throws Exception {
-    {
-
-      managingVM.invoke(new SerializableCallable("Compact All Disk Stores Remote") {
-
-        public Object call() throws Exception {
-          GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-          Set<DistributedMember> otherMemberSet =
-              cache.getDistributionManager().getOtherNormalDistributionManagerIds();
-
-          for (DistributedMember member : otherMemberSet) {
-            MemberMXBean bean = MBeanUtil.getMemberMbeanProxy(member);
-            String[] allDisks = bean.listDiskStores(true);
-            assertNotNull(allDisks);
-            List<String> listString = Arrays.asList(allDisks);
-            org.apache.geode.test.dunit.LogWriterUtils.getLogWriter()
-                .info("<ExpectedString> Remote All Disk Stores Are  " + listString.toString()
-                    + "</ExpectedString> ");
-            String[] compactedDiskStores = bean.compactAllDiskStores();
-            assertTrue(compactedDiskStores.length > 0);
-            for (int i = 0; i < compactedDiskStores.length; i++) {
-              org.apache.geode.test.dunit.LogWriterUtils.getLogWriter()
-                  .info("<ExpectedString> Remote Compacted Store " + i + " "
-                      + compactedDiskStores[i] + "</ExpectedString> ");
-            }
-
-          }
-          return null;
-        }
-      });
+  private void compactDiskStoresRemote(final VM managerVM, final int memberCount) {
+    managerVM.invoke("compactDiskStoresRemote", () -> {
+      Set<DistributedMember> otherMemberSet = this.managementTestRule.getOtherNormalMembers();// ((GemFireCacheImpl)cache).getDistributionManager().getOtherNormalDistributionManagerIds();
+      assertThat(otherMemberSet.size()).isEqualTo(memberCount);
 
-    }
+      SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
-  }
-
-  /**
-   * Checks if a file with the given extension is present
-   * 
-   * @param fileExtension file extension
-   * @throws Exception
-   */
-  protected void checkIfContainsFileWithExt(String fileExtension) throws Exception {
-    File[] files = diskDir.listFiles();
-    for (int j = 0; j < files.length; j++) {
-      if (files[j].getAbsolutePath().endsWith(fileExtension)) {
-        fail("file \"" + files[j].getAbsolutePath() + "\" still exists");
-      }
-    }
+      for (DistributedMember member : otherMemberSet) {
+        MemberMXBean memberMXBean = awaitMemberMXBeanProxy(member);
 
-  }
+        String[] allDisks = memberMXBean.listDiskStores(true);
+        assertThat(allDisks).isNotNull().hasSize(1);
 
-  /**
-   * Update Entry
-   * 
-   * @param vm1 reference to VM
-   */
-  protected void updateTheEntry(VM vm1) {
-    updateTheEntry(vm1, "C");
-  }
-
-  /**
-   * Update an Entry
-   * 
-   * @param vm1 reference to VM
-   * @param value Value which is updated
-   */
-  @SuppressWarnings("serial")
-  protected void updateTheEntry(VM vm1, final String value) {
-    vm1.invoke(new SerializableRunnable("change the entry") {
-
-      public void run() {
-        Cache cache = getCache();
-        Region region = cache.getRegion(REGION_NAME);
-        region.put("A", value);
+        String[] compactedDiskStores = memberMXBean.compactAllDiskStores();
+        assertThat(compactedDiskStores).hasSize(1);
       }
     });
   }
 
-  /**
-   * Put an entry to region
-   * 
-   * @param vm0 reference to VM
-   */
-  @SuppressWarnings("serial")
-  protected void putAnEntry(VM vm0) {
-    vm0.invoke(new SerializableRunnable("Put an entry") {
-
-      public void run() {
-        Cache cache = getCache();
-        Region region = cache.getRegion(REGION_NAME);
-        region.put("A", "B");
-      }
+  private void updateTheEntry(final VM memberVM, final String value) {
+    memberVM.invoke("updateTheEntry", () -> {
+      Cache cache = this.managementTestRule.getCache();
+      Region region = cache.getRegion(REGION_NAME);
+      region.put("A", value);
     });
   }
 
-  /**
-   * Close the given region REGION_NAME
-   * 
-   * @param vm reference to VM
-   */
-  @SuppressWarnings("serial")
-  protected void closeRegion(final VM vm) {
-    SerializableRunnable closeRegion = new SerializableRunnable("Close persistent region") {
-      public void run() {
-        Cache cache = getCache();
-        Region region = cache.getRegion(REGION_NAME);
-        region.close();
-      }
-    };
-    vm.invoke(closeRegion);
+  private void putAnEntry(final VM memberVM) {
+    memberVM.invoke("putAnEntry", () -> {
+      Cache cache = managementTestRule.getCache();
+      Region region = cache.getRegion(REGION_NAME);
+      region.put("A", "B");
+    });
   }
 
-  /**
-   * Waiting to blocked waiting for another persistent member to come online
-   * 
-   * @param vm reference to VM
-   */
-  @SuppressWarnings("serial")
-  private void waitForBlockedInitialization(VM vm) {
-    vm.invoke(new SerializableRunnable() {
-
-      public void run() {
-        Wait.waitForCriterion(new WaitCriterion() {
-
-          public String description() {
-            return "Waiting to blocked waiting for another persistent member to come online";
-          }
-
-          public boolean done() {
-            Cache cache = getCache();
-            GemFireCacheImpl cacheImpl = (GemFireCacheImpl) cache;
-            PersistentMemberManager mm = cacheImpl.getPersistentMemberManager();
-            Map<String, Set<PersistentMemberID>> regions = mm.getWaitingRegions();
-            boolean done = !regions.isEmpty();
-            return done;
-          }
-
-        }, MAX_WAIT, 100, true);
-
-      }
-
+  private void closeRegion(final VM memberVM) {
+    memberVM.invoke("closeRegion", () -> {
+      Cache cache = this.managementTestRule.getCache();
+      Region region = cache.getRegion(REGION_NAME);
+      region.close();
     });
   }
 
-  /**
-   * Creates a persistent region
-   * 
-   * @param vm reference to VM
-   * @throws Throwable
-   */
-  protected void createPersistentRegion(VM vm) throws Throwable {
-    AsyncInvocation future = createPersistentRegionAsync(vm);
-    future.join(MAX_WAIT);
-    if (future.isAlive()) {
-      fail("Region not created within" + MAX_WAIT);
-    }
-    if (future.exceptionOccurred()) {
-      throw new RuntimeException(future.getException());
-    }
+  private void createPersistentRegion(final VM memberVM)
+      throws InterruptedException, ExecutionException, TimeoutException {
+    await(createPersistentRegionAsync(memberVM));
   }
 
-  /**
-   * Creates a persistent region in async manner
-   * 
-   * @param vm reference to VM
-   * @return reference to AsyncInvocation
-   */
-  @SuppressWarnings("serial")
-  protected AsyncInvocation createPersistentRegionAsync(final VM vm) {
-    SerializableRunnable createRegion = new SerializableRunnable("Create persistent region") {
-      public void run() {
-        Cache cache = getCache();
-        DiskStoreFactory dsf = cache.createDiskStoreFactory();
-        File dir = getDiskDirForVM(vm);
-        dir.mkdirs();
-        dsf.setDiskDirs(new File[] {dir});
-        dsf.setMaxOplogSize(1);
-        dsf.setAllowForceCompaction(true);
-        dsf.setAutoCompact(false);
-        DiskStore ds = dsf.create(REGION_NAME);
-        RegionFactory rf = cache.createRegionFactory();
-        rf.setDiskStoreName(ds.getName());
-        rf.setDiskSynchronous(true);
-        rf.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE);
-        rf.setScope(Scope.DISTRIBUTED_ACK);
-        rf.create(REGION_NAME);
-      }
-    };
-    return vm.invokeAsync(createRegion);
+  private AsyncInvocation createPersistentRegionAsync(final VM memberVM) {
+    return memberVM.invokeAsync("createPersistentRegionAsync", () -> {
+      File dir = new File(diskDir, String.valueOf(ProcessUtils.identifyPid()));
+
+      Cache cache = this.managementTestRule.getCache();
+
+      DiskStoreFactory diskStoreFactory = cache.createDiskStoreFactory();
+      diskStoreFactory.setDiskDirs(new File[] {dir});
+      diskStoreFactory.setMaxOplogSize(1);
+      diskStoreFactory.setAllowForceCompaction(true);
+      diskStoreFactory.setAutoCompact(false);
+      DiskStore diskStore = diskStoreFactory.create(REGION_NAME);
+
+      RegionFactory regionFactory = cache.createRegionFactory();
+      regionFactory.setDiskStoreName(diskStore.getName());
+      regionFactory.setDiskSynchronous(true);
+      regionFactory.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE);
+      regionFactory.setScope(Scope.DISTRIBUTED_ACK);
+      regionFactory.create(REGION_NAME);
+    });
   }
 
-  /**
-   * Validates a persistent region
-   * 
-   * @param vm reference to VM
-   */
-  @SuppressWarnings("serial")
-  protected void validatePersistentRegion(final VM vm) {
-    SerializableRunnable validateDisk = new SerializableRunnable("Validate persistent region") {
-      public void run() {
-        Cache cache = getCache();
-        ManagementService service = getManagementService();
-        DiskStoreMXBean bean = service.getLocalDiskStoreMBean(REGION_NAME);
-        assertNotNull(bean);
+  private void verifyRecoveryStats(final VM memberVM, final boolean localRecovery) {
+    memberVM.invoke("verifyRecoveryStats", () -> {
+      Cache cache = this.managementTestRule.getCache();
+      Region region = cache.getRegion(REGION_NAME);
+      DistributedRegion distributedRegion = (DistributedRegion) region;
+      DiskRegionStats stats = distributedRegion.getDiskRegion().getStats();
+
+      if (localRecovery) {
+        assertThat(stats.getLocalInitializations()).isEqualTo(1);
+        assertThat(stats.getRemoteInitializations()).isEqualTo(0);
+      } else {
+        assertThat(stats.getLocalInitializations()).isEqualTo(0);
+        assertThat(stats.getRemoteInitializations()).isEqualTo(1);
       }
-    };
-    vm.invoke(validateDisk);
+    });
   }
 
-  /**
-   * Appends vm id to disk dir
-   * 
-   * @param vm reference to VM
-   * @return
-   */
-  protected File getDiskDirForVM(final VM vm) {
-    File dir = new File(diskDir, String.valueOf(vm.getPid()));
-    return dir;
+  private MemberMXBean awaitMemberMXBeanProxy(final DistributedMember member) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    ObjectName objectName = service.getMemberMBeanName(member);
+    await()
+        .until(() -> assertThat(service.getMBeanProxy(objectName, MemberMXBean.class)).isNotNull());
+    return service.getMBeanProxy(objectName, MemberMXBean.class);
   }
 
-  /**
-   * Checks recovery status
-   * 
-   * @param vm reference to VM
-   * @param localRecovery local recovery on or not
-   */
-  @SuppressWarnings("serial")
-  private void checkForRecoveryStat(VM vm, final boolean localRecovery) {
-    vm.invoke(new SerializableRunnable("check disk region stat") {
-
-      public void run() {
-        Cache cache = getCache();
-        Region region = cache.getRegion(REGION_NAME);
-        DistributedRegion distributedRegion = (DistributedRegion) region;
-        DiskRegionStats stats = distributedRegion.getDiskRegion().getStats();
-        if (localRecovery) {
-          assertEquals(1, stats.getLocalInitializations());
-          assertEquals(0, stats.getRemoteInitializations());
-        } else {
-          assertEquals(0, stats.getLocalInitializations());
-          assertEquals(1, stats.getRemoteInitializations());
-        }
-
-      }
-    });
+  private void await(final AsyncInvocation createPersistentRegionAsync)
+      throws InterruptedException, ExecutionException, TimeoutException {
+    createPersistentRegionAsync.await(2, MINUTES);
   }
 
-  /**
-   * 
-   * @return back up directory
-   */
-  protected static File getBackupDir(String name) throws Exception {
-    File backUpDir = new File("BackupDir-" + name).getAbsoluteFile();
-    org.apache.geode.internal.FileUtil.delete(backUpDir);
-    backUpDir.mkdir();
-    backUpDir.deleteOnExit();
-    return backUpDir;
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(2, MINUTES);
   }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/DistributedSystemDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/DistributedSystemDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/DistributedSystemDUnitTest.java
index 4eaba67..79a4ce4 100644
--- a/geode-core/src/test/java/org/apache/geode/management/DistributedSystemDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/DistributedSystemDUnitTest.java
@@ -14,23 +14,19 @@
  */
 package org.apache.geode.management;
 
-import org.junit.experimental.categories.Category;
-import org.junit.Test;
-
-import static org.junit.Assert.*;
-
-import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
+import static java.util.concurrent.TimeUnit.*;
+import static org.apache.geode.test.dunit.Host.*;
+import static org.apache.geode.test.dunit.Invoke.*;
+import static org.assertj.core.api.Assertions.*;
 
+import java.io.Serializable;
+import java.lang.management.ManagementFactory;
 import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
-import javax.management.InstanceNotFoundException;
 import javax.management.ListenerNotFoundException;
 import javax.management.MBeanServer;
 import javax.management.Notification;
@@ -39,11 +35,16 @@ import javax.management.NotificationFilter;
 import javax.management.NotificationListener;
 import javax.management.ObjectName;
 
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
 import org.apache.logging.log4j.Logger;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
 
-import org.apache.geode.cache.Cache;
 import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.InternalDistributedSystem;
 import org.apache.geode.internal.admin.Alert;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.internal.logging.LogService;
@@ -57,428 +58,277 @@ import org.apache.geode.management.internal.SystemManagementService;
 import org.apache.geode.management.internal.beans.MemberMBean;
 import org.apache.geode.management.internal.beans.SequenceNumber;
 import org.apache.geode.test.dunit.IgnoredException;
-import org.apache.geode.test.dunit.LogWriterUtils;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.SerializableCallable;
-import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
+import org.apache.geode.test.junit.categories.DistributedTest;
 
 /**
- * Distributed System tests
- * 
- * a) For all the notifications
- * 
- * i) gemfire.distributedsystem.member.joined
- * 
- * ii) gemfire.distributedsystem.member.left
- * 
- * iii) gemfire.distributedsystem.member.suspect
- * 
- * iv ) All notifications emitted by member mbeans
- * 
- * vi) Alerts
- * 
+ * Distributed System management tests
+ * <p>
+ * a) For all the notifications i) gemfire.distributedsystem.member.joined ii)
+ * gemfire.distributedsystem.member.left iii) gemfire.distributedsystem.member.suspect iv ) All
+ * notifications emitted by member mbeans vi) Alerts
+ * <p>
  * b) Concurrently modify proxy list by removing member and accessing the distributed system MBean
- * 
+ * <p>
  * c) Aggregate Operations like shutDownAll
- * 
+ * <p>
  * d) Member level operations like fetchJVMMetrics()
- * 
+ * <p>
  * e ) Statistics
- * 
- * 
- * 
  */
 @Category(DistributedTest.class)
-public class DistributedSystemDUnitTest extends ManagementTestBase {
+@SuppressWarnings({"serial", "unused"})
+public class DistributedSystemDUnitTest implements Serializable {
 
   private static final Logger logger = LogService.getLogger();
 
-  private static final long serialVersionUID = 1L;
-
+  private static final String WARNING_LEVEL_MESSAGE = "Warning Level Alert Message";
+  private static final String SEVERE_LEVEL_MESSAGE = "Severe Level Alert Message";
 
-  private static final int MAX_WAIT = 10 * 1000;
+  private static List<Notification> notifications;
+  private static Map<ObjectName, NotificationListener> notificationListenerMap;
 
-  private static MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
+  @Manager
+  private VM managerVM;
 
-  static List<Notification> notifList = new ArrayList<>();
+  @Member
+  private VM[] memberVMs;
 
-  static Map<ObjectName, NotificationListener> notificationListenerMap =
-      new HashMap<ObjectName, NotificationListener>();
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().build();
 
-  static final String WARNING_LEVEL_MESSAGE = "Warninglevel Alert Message";
-
-  static final String SEVERE_LEVEL_MESSAGE = "Severelevel Alert Message";
+  @Before
+  public void before() throws Exception {
+    notifications = new ArrayList<>();
+    notificationListenerMap = new HashMap<>();
 
+    invokeInEveryVM(() -> notifications = new ArrayList<>());
+    invokeInEveryVM(() -> notificationListenerMap = new HashMap<>());
+  }
 
-  public DistributedSystemDUnitTest() {
-    super();
+  @After
+  public void after() throws Exception {
+    resetAlertCounts(this.managerVM);
   }
 
   /**
    * Tests each and every operations that is defined on the MemberMXBean
-   * 
-   * @throws Exception
    */
   @Test
   public void testDistributedSystemAggregate() throws Exception {
-    VM managingNode = getManagingNode();
-    createManagementCache(managingNode);
-    startManagingNode(managingNode);
-    addNotificationListener(managingNode);
+    this.managementTestRule.createManager(this.managerVM);
+    addNotificationListener(this.managerVM);
 
-    for (VM vm : getManagedNodeList()) {
-      createCache(vm);
+    for (VM memberVM : this.memberVMs) {
+      this.managementTestRule.createMember(memberVM);
     }
 
-    checkAggregate(managingNode);
-    for (VM vm : getManagedNodeList()) {
-      closeCache(vm);
-    }
-
-    closeCache(managingNode);
-
+    verifyDistributedSystemMXBean(this.managerVM);
   }
 
   /**
    * Tests each and every operations that is defined on the MemberMXBean
-   * 
-   * @throws Exception
    */
   @Test
   public void testAlertManagedNodeFirst() throws Exception {
-
-    for (VM vm : getManagedNodeList()) {
-      createCache(vm);
-      warnLevelAlert(vm);
-      severeLevelAlert(vm);
+    for (VM memberVM : this.memberVMs) {
+      this.managementTestRule.createMember(memberVM);
+      generateWarningAlert(memberVM);
+      generateSevereAlert(memberVM);
     }
 
-    VM managingNode = getManagingNode();
-
-    createManagementCache(managingNode);
-    startManagingNode(managingNode);
-    addAlertListener(managingNode);
-    checkAlertCount(managingNode, 0, 0);
+    this.managementTestRule.createManager(this.managerVM);
+    addAlertListener(this.managerVM);
+    verifyAlertCount(this.managerVM, 0, 0);
 
-    final DistributedMember managingMember = getMember(managingNode);
+    DistributedMember managerDistributedMember =
+        this.managementTestRule.getDistributedMember(this.managerVM);
 
     // Before we start we need to ensure that the initial (implicit) SEVERE alert has propagated
     // everywhere.
-    for (VM vm : getManagedNodeList()) {
-      ensureLoggerState(vm, managingMember, Alert.SEVERE);
+    for (VM memberVM : this.memberVMs) {
+      verifyAlertAppender(memberVM, managerDistributedMember, Alert.SEVERE);
     }
 
-    setAlertLevel(managingNode, AlertDetails.getAlertLevelAsString(Alert.WARNING));
+    setAlertLevel(this.managerVM, AlertDetails.getAlertLevelAsString(Alert.WARNING));
 
-    for (VM vm : getManagedNodeList()) {
-      ensureLoggerState(vm, managingMember, Alert.WARNING);
-      warnLevelAlert(vm);
-      severeLevelAlert(vm);
+    for (VM memberVM : this.memberVMs) {
+      verifyAlertAppender(memberVM, managerDistributedMember, Alert.WARNING);
+      generateWarningAlert(memberVM);
+      generateSevereAlert(memberVM);
     }
 
-    checkAlertCount(managingNode, 3, 3);
-    resetAlertCounts(managingNode);
+    verifyAlertCount(this.managerVM, 3, 3);
+    resetAlertCounts(this.managerVM);
 
-    setAlertLevel(managingNode, AlertDetails.getAlertLevelAsString(Alert.SEVERE));
+    setAlertLevel(this.managerVM, AlertDetails.getAlertLevelAsString(Alert.SEVERE));
 
-    for (VM vm : getManagedNodeList()) {
-      ensureLoggerState(vm, managingMember, Alert.SEVERE);
-      warnLevelAlert(vm);
-      severeLevelAlert(vm);
+    for (VM memberVM : this.memberVMs) {
+      verifyAlertAppender(memberVM, managerDistributedMember, Alert.SEVERE);
+      generateWarningAlert(memberVM);
+      generateSevereAlert(memberVM);
     }
 
-    checkAlertCount(managingNode, 3, 0);
-    resetAlertCounts(managingNode);
-
-    for (VM vm : getManagedNodeList()) {
-      closeCache(vm);
-    }
-
-    closeCache(managingNode);
-  }
-
-  @SuppressWarnings("serial")
-  public void ensureLoggerState(VM vm1, final DistributedMember member, final int alertLevel)
-      throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Ensure Logger State") {
-
-        public Object call() throws Exception {
-
-          Wait.waitForCriterion(new WaitCriterion() {
-            public String description() {
-              return "Waiting for all alert Listener to register with managed node";
-            }
-
-            public boolean done() {
-
-              if (AlertAppender.getInstance().hasAlertListener(member, alertLevel)) {
-                return true;
-              }
-              return false;
-            }
-
-          }, MAX_WAIT, 500, true);
-
-          return null;
-        }
-      });
-
-    }
+    verifyAlertCount(this.managerVM, 3, 0);
   }
 
   /**
    * Tests each and every operations that is defined on the MemberMXBean
-   * 
-   * @throws Exception
    */
   @Test
   public void testShutdownAll() throws Exception {
-    final Host host = Host.getHost(0);
-    VM managedNode1 = host.getVM(0);
-    VM managedNode2 = host.getVM(1);
-    VM managedNode3 = host.getVM(2);
-
-    VM managingNode = host.getVM(3);
-
-    // Managing Node is created first
-    createManagementCache(managingNode);
-    startManagingNode(managingNode);
-
-    createCache(managedNode1);
-    createCache(managedNode2);
-    createCache(managedNode3);
-    shutDownAll(managingNode);
-    closeCache(managingNode);
+    VM memberVM1 = getHost(0).getVM(0);
+    VM memberVM2 = getHost(0).getVM(1);
+    VM memberVM3 = getHost(0).getVM(2);
+
+    VM managerVM = getHost(0).getVM(3);
+
+    // managerVM Node is created first
+    this.managementTestRule.createManager(managerVM);
+
+    this.managementTestRule.createMember(memberVM1);
+    this.managementTestRule.createMember(memberVM2);
+    this.managementTestRule.createMember(memberVM3);
+
+    shutDownAll(managerVM);
   }
 
   @Test
   public void testNavigationAPIS() throws Exception {
+    this.managementTestRule.createManager(this.managerVM);
 
-    final Host host = Host.getHost(0);
-
-    createManagementCache(managingNode);
-    startManagingNode(managingNode);
-
-    for (VM vm : managedNodeList) {
-      createCache(vm);
+    for (VM memberVM : this.memberVMs) {
+      this.managementTestRule.createMember(memberVM);
     }
 
-    checkNavigationAPIs(managingNode);
+    verifyFetchMemberObjectName(this.managerVM, this.memberVMs.length + 1);
   }
 
   @Test
   public void testNotificationHub() throws Exception {
-    this.initManagement(false);
+    this.managementTestRule.createMembers();
+    this.managementTestRule.createManagers();
 
     class NotificationHubTestListener implements NotificationListener {
+
       @Override
       public synchronized void handleNotification(Notification notification, Object handback) {
         logger.info("Notification received {}", notification);
-        notifList.add(notification);
+        notifications.add(notification);
       }
     }
 
-    managingNode.invoke(new SerializableRunnable("Add Listener to MemberMXBean") {
-
-      public void run() {
-        Cache cache = getCache();
-        ManagementService service = getManagementService();
-        final DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-
-        Wait.waitForCriterion(new WaitCriterion() {
-          public String description() {
-            return "Waiting for all members to send their initial Data";
-          }
-
-          public boolean done() {
-            if (bean.listMemberObjectNames().length == 5) {// including locator
-              return true;
-            } else {
-              return false;
-            }
-          }
-        }, MAX_WAIT, 500, true);
-        for (ObjectName objectName : bean.listMemberObjectNames()) {
-          NotificationHubTestListener listener = new NotificationHubTestListener();
-          try {
-            mbeanServer.addNotificationListener(objectName, listener, null, null);
-            notificationListenerMap.put(objectName, listener);
-          } catch (InstanceNotFoundException e) {
-            LogWriterUtils.getLogWriter().error(e);
-          }
-        }
+    this.managerVM.invoke("addListenerToMemberMXBean", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      final DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+
+      await().until(() -> assertThat(distributedSystemMXBean.listMemberObjectNames()).hasSize(5));
+
+      for (ObjectName objectName : distributedSystemMXBean.listMemberObjectNames()) {
+        NotificationHubTestListener listener = new NotificationHubTestListener();
+        ManagementFactory.getPlatformMBeanServer().addNotificationListener(objectName, listener,
+            null, null);
+        notificationListenerMap.put(objectName, listener);
       }
     });
 
     // Check in all VMS
 
-    for (VM vm : managedNodeList) {
-      vm.invoke(new SerializableRunnable("Check Hub Listener num count") {
-
-        public void run() {
-          Cache cache = getCache();
-          SystemManagementService service = (SystemManagementService) getManagementService();
-          NotificationHub hub = service.getNotificationHub();
-          Map<ObjectName, NotificationHubListener> listenerObjectMap = hub.getListenerObjectMap();
-          assertEquals(1, listenerObjectMap.keySet().size());
-          ObjectName memberMBeanName = MBeanJMXAdapter
-              .getMemberMBeanName(cache.getDistributedSystem().getDistributedMember());
-
-          NotificationHubListener listener = listenerObjectMap.get(memberMBeanName);
-
-          /*
-           * Counter of listener should be 2 . One for default Listener which is added for each
-           * member mbean by distributed system mbean One for the added listener in test
-           */
-          assertEquals(2, listener.getNumCounter());
-
-          // Raise some notifications
-
-          NotificationBroadcasterSupport memberLevelNotifEmitter =
-              (MemberMBean) service.getMemberMXBean();
-
-          String memberSource = MBeanJMXAdapter
-              .getMemberNameOrId(cache.getDistributedSystem().getDistributedMember());
-
-          // Only a dummy notification , no actual region is creates
-          Notification notification = new Notification(JMXNotificationType.REGION_CREATED,
-              memberSource, SequenceNumber.next(), System.currentTimeMillis(),
-              ManagementConstants.REGION_CREATED_PREFIX + "/test");
-          memberLevelNotifEmitter.sendNotification(notification);
-
-        }
+    for (VM memberVM : this.memberVMs) {
+      memberVM.invoke("checkNotificationHubListenerCount", () -> {
+        SystemManagementService service = this.managementTestRule.getSystemManagementService();
+        NotificationHub notificationHub = service.getNotificationHub();
+        Map<ObjectName, NotificationHubListener> listenerMap =
+            notificationHub.getListenerObjectMap();
+        assertThat(listenerMap.keySet()).hasSize(1);
+
+        ObjectName memberMBeanName =
+            MBeanJMXAdapter.getMemberMBeanName(this.managementTestRule.getDistributedMember());
+        NotificationHubListener listener = listenerMap.get(memberMBeanName);
+
+        /*
+         * Counter of listener should be 2 . One for default Listener which is added for each member
+         * mbean by distributed system mbean One for the added listener in test
+         */
+        assertThat(listener.getNumCounter()).isEqualTo(2);
+
+        // Raise some notifications
+
+        NotificationBroadcasterSupport notifier = (MemberMBean) service.getMemberMXBean();
+        String memberSource =
+            MBeanJMXAdapter.getMemberNameOrId(this.managementTestRule.getDistributedMember());
+
+        // Only a dummy notification , no actual region is created
+        Notification notification = new Notification(JMXNotificationType.REGION_CREATED,
+            memberSource, SequenceNumber.next(), System.currentTimeMillis(),
+            ManagementConstants.REGION_CREATED_PREFIX + "/test");
+        notifier.sendNotification(notification);
       });
     }
 
-    managingNode.invoke(new SerializableRunnable("Check notifications && Remove Listeners") {
-
-      public void run() {
-
-        Wait.waitForCriterion(new WaitCriterion() {
-          public String description() {
-            return "Waiting for all Notifications to reach the Managing Node";
-          }
-
-          public boolean done() {
-            if (notifList.size() == 3) {
-              return true;
-            } else {
-              return false;
-            }
-          }
-        }, MAX_WAIT, 500, true);
-
-        notifList.clear();
+    this.managerVM.invoke("checkNotificationsAndRemoveListeners", () -> {
+      await().until(() -> assertThat(notifications).hasSize(3));
 
-        Iterator<ObjectName> it = notificationListenerMap.keySet().iterator();
-        while (it.hasNext()) {
-          ObjectName objectName = it.next();
-          NotificationListener listener = notificationListenerMap.get(objectName);
-          try {
-            mbeanServer.removeNotificationListener(objectName, listener);
-          } catch (ListenerNotFoundException e) {
-            LogWriterUtils.getLogWriter().error(e);
-          } catch (InstanceNotFoundException e) {
-            LogWriterUtils.getLogWriter().error(e);
-          }
-        }
+      notifications.clear();
 
+      for (ObjectName objectName : notificationListenerMap.keySet()) {
+        NotificationListener listener = notificationListenerMap.get(objectName);
+        ManagementFactory.getPlatformMBeanServer().removeNotificationListener(objectName, listener);
       }
     });
 
     // Check in all VMS again
 
-    for (VM vm : managedNodeList) {
-      vm.invoke(new SerializableRunnable("Check Hub Listener num count Again") {
-
-        public void run() {
-          Cache cache = getCache();
-          SystemManagementService service = (SystemManagementService) getManagementService();
-          NotificationHub hub = service.getNotificationHub();
-          Map<ObjectName, NotificationHubListener> listenerObjectMap = hub.getListenerObjectMap();
-
-          assertEquals(1, listenerObjectMap.keySet().size());
-
-          ObjectName memberMBeanName = MBeanJMXAdapter
-              .getMemberMBeanName(cache.getDistributedSystem().getDistributedMember());
-
-          NotificationHubListener listener = listenerObjectMap.get(memberMBeanName);
-
-          /*
-           * Counter of listener should be 1 for the default Listener which is added for each member
-           * mbean by distributed system mbean.
-           */
-          assertEquals(1, listener.getNumCounter());
-
-        }
+    for (VM memberVM : this.memberVMs) {
+      memberVM.invoke("checkNotificationHubListenerCountAgain", () -> {
+        SystemManagementService service = this.managementTestRule.getSystemManagementService();
+        NotificationHub hub = service.getNotificationHub();
+        Map<ObjectName, NotificationHubListener> listenerObjectMap = hub.getListenerObjectMap();
+        assertThat(listenerObjectMap.keySet().size()).isEqualTo(1);
+
+        ObjectName memberMBeanName =
+            MBeanJMXAdapter.getMemberMBeanName(this.managementTestRule.getDistributedMember());
+        NotificationHubListener listener = listenerObjectMap.get(memberMBeanName);
+
+        /*
+         * Counter of listener should be 1 for the default Listener which is added for each member
+         * mbean by distributed system mbean.
+         */
+        assertThat(listener.getNumCounter()).isEqualTo(1);
       });
     }
 
-    managingNode.invoke(new SerializableRunnable("Remove Listener from MemberMXBean") {
-
-      public void run() {
-        Cache cache = getCache();
-        ManagementService service = getManagementService();
-        final DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-
-        Wait.waitForCriterion(new WaitCriterion() {
-          public String description() {
-            return "Waiting for all members to send their initial Data";
-          }
-
-          public boolean done() {
-            if (bean.listMemberObjectNames().length == 5) {// including locator
-              return true;
-            } else {
-              return false;
-            }
-
-          }
-
-        }, MAX_WAIT, 500, true);
-        for (ObjectName objectName : bean.listMemberObjectNames()) {
-          NotificationHubTestListener listener = new NotificationHubTestListener();
-          try {
-            mbeanServer.removeNotificationListener(objectName, listener);
-          } catch (InstanceNotFoundException e) {
-            LogWriterUtils.getLogWriter().error(e);
-          } catch (ListenerNotFoundException e) {
-            // TODO: apparently there is never a notification listener on any these mbeans at this
-            // point
-            // fix this test so it doesn't hit these unexpected exceptions --
-            // getLogWriter().error(e);
-          }
+    this.managerVM.invoke("removeListenerFromMemberMXBean", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+
+      await().until(() -> assertThat(distributedSystemMXBean.listMemberObjectNames()).hasSize(5));
+
+      for (ObjectName objectName : distributedSystemMXBean.listMemberObjectNames()) {
+        NotificationHubTestListener listener = new NotificationHubTestListener();
+        try {
+          ManagementFactory.getPlatformMBeanServer().removeNotificationListener(objectName,
+              listener); // because new instance!!
+        } catch (ListenerNotFoundException e) {
+          // TODO: [old] apparently there is never a notification listener on any these mbeans at
+          // this point [fix this]
+          // fix this test so it doesn't hit these unexpected exceptions -- getLogWriter().error(e);
         }
       }
     });
 
-    for (VM vm : managedNodeList) {
-      vm.invoke(new SerializableRunnable("Check Hub Listeners clean up") {
-
-        public void run() {
-          Cache cache = getCache();
-          SystemManagementService service = (SystemManagementService) getManagementService();
-          NotificationHub hub = service.getNotificationHub();
-          hub.cleanUpListeners();
-          assertEquals(0, hub.getListenerObjectMap().size());
-
-          Iterator<ObjectName> it = notificationListenerMap.keySet().iterator();
-          while (it.hasNext()) {
-            ObjectName objectName = it.next();
-            NotificationListener listener = notificationListenerMap.get(objectName);
-            try {
-              mbeanServer.removeNotificationListener(objectName, listener);
-              fail("Found Listeners inspite of clearing them");
-            } catch (ListenerNotFoundException e) {
-              // Expected Exception Do nothing
-            } catch (InstanceNotFoundException e) {
-              LogWriterUtils.getLogWriter().error(e);
-            }
-          }
+    for (VM memberVM : this.memberVMs) {
+      memberVM.invoke("verifyNotificationHubListenersWereRemoved", () -> {
+        SystemManagementService service = this.managementTestRule.getSystemManagementService();
+        NotificationHub notificationHub = service.getNotificationHub();
+        notificationHub.cleanUpListeners();
+        assertThat(notificationHub.getListenerObjectMap()).isEmpty();
+
+        for (ObjectName objectName : notificationListenerMap.keySet()) {
+          NotificationListener listener = notificationListenerMap.get(objectName);
+          assertThatThrownBy(() -> ManagementFactory.getPlatformMBeanServer()
+              .removeNotificationListener(objectName, listener))
+                  .isExactlyInstanceOf(ListenerNotFoundException.class);
         }
       });
     }
@@ -486,404 +336,229 @@ public class DistributedSystemDUnitTest extends ManagementTestBase {
 
   /**
    * Tests each and every operations that is defined on the MemberMXBean
-   * 
-   * @throws Exception
    */
   @Test
   public void testAlert() throws Exception {
-    VM managingNode = getManagingNode();
-
-    createManagementCache(managingNode);
-    startManagingNode(managingNode);
-    addAlertListener(managingNode);
-    resetAlertCounts(managingNode);
-
-    final DistributedMember managingMember = getMember(managingNode);
-
-
+    this.managementTestRule.createManager(this.managerVM);
+    addAlertListener(this.managerVM);
+    resetAlertCounts(this.managerVM);
 
-    warnLevelAlert(managingNode);
-    severeLevelAlert(managingNode);
-    checkAlertCount(managingNode, 1, 0);
-    resetAlertCounts(managingNode);
+    DistributedMember managerDistributedMember =
+        this.managementTestRule.getDistributedMember(this.managerVM);
 
-    for (VM vm : getManagedNodeList()) {
+    generateWarningAlert(this.managerVM);
+    generateSevereAlert(this.managerVM);
+    verifyAlertCount(this.managerVM, 1, 0);
+    resetAlertCounts(this.managerVM);
 
-      createCache(vm);
-      // Default is severe ,So only Severe level alert is expected
+    for (VM memberVM : this.memberVMs) {
+      this.managementTestRule.createMember(memberVM);
 
-      ensureLoggerState(vm, managingMember, Alert.SEVERE);
-
-      warnLevelAlert(vm);
-      severeLevelAlert(vm);
+      verifyAlertAppender(memberVM, managerDistributedMember, Alert.SEVERE);
 
+      generateWarningAlert(memberVM);
+      generateSevereAlert(memberVM);
     }
-    checkAlertCount(managingNode, 3, 0);
-    resetAlertCounts(managingNode);
-    setAlertLevel(managingNode, AlertDetails.getAlertLevelAsString(Alert.WARNING));
 
+    verifyAlertCount(this.managerVM, 3, 0);
+    resetAlertCounts(this.managerVM);
+    setAlertLevel(this.managerVM, AlertDetails.getAlertLevelAsString(Alert.WARNING));
 
-    for (VM vm : getManagedNodeList()) {
-      // warning and severe alerts both are to be checked
-      ensureLoggerState(vm, managingMember, Alert.WARNING);
-      warnLevelAlert(vm);
-      severeLevelAlert(vm);
+    for (VM memberVM : this.memberVMs) {
+      verifyAlertAppender(memberVM, managerDistributedMember, Alert.WARNING);
+      generateWarningAlert(memberVM);
+      generateSevereAlert(memberVM);
     }
 
-    checkAlertCount(managingNode, 3, 3);
-
-    resetAlertCounts(managingNode);
+    verifyAlertCount(this.managerVM, 3, 3);
 
-    setAlertLevel(managingNode, AlertDetails.getAlertLevelAsString(Alert.OFF));
+    resetAlertCounts(this.managerVM);
 
-    for (VM vm : getManagedNodeList()) {
-      ensureLoggerState(vm, managingMember, Alert.OFF);
-      warnLevelAlert(vm);
-      severeLevelAlert(vm);
-    }
-    checkAlertCount(managingNode, 0, 0);
-    resetAlertCounts(managingNode);
+    setAlertLevel(this.managerVM, AlertDetails.getAlertLevelAsString(Alert.OFF));
 
-    for (VM vm : getManagedNodeList()) {
-      closeCache(vm);
+    for (VM memberVM : this.memberVMs) {
+      verifyAlertAppender(memberVM, managerDistributedMember, Alert.OFF);
+      generateWarningAlert(memberVM);
+      generateSevereAlert(memberVM);
     }
 
-    closeCache(managingNode);
-
+    verifyAlertCount(this.managerVM, 0, 0);
   }
 
-  @SuppressWarnings("serial")
-  public void checkAlertCount(VM vm1, final int expectedSevereAlertCount,
-      final int expectedWarningAlertCount) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Check Alert Count") {
-
-        public Object call() throws Exception {
-          final AlertNotifListener nt = AlertNotifListener.getInstance();
-          Wait.waitForCriterion(new WaitCriterion() {
-            public String description() {
-              return "Waiting for all alerts to reach the Managing Node";
-            }
-
-            public boolean done() {
-              if (expectedSevereAlertCount == nt.getseverAlertCount()
-                  && expectedWarningAlertCount == nt.getWarnigAlertCount()) {
-                return true;
-              } else {
-                return false;
-              }
-
-            }
-
-          }, MAX_WAIT, 500, true);
-
-          return null;
-        }
-      });
-
-    }
+  private void verifyAlertAppender(final VM memberVM, final DistributedMember member,
+      final int alertLevel) {
+    memberVM.invoke("verifyAlertAppender",
+        () -> await().until(
+            () -> assertThat(AlertAppender.getInstance().hasAlertListener(member, alertLevel))
+                .isTrue()));
   }
 
+  private void verifyAlertCount(final VM managerVM, final int expectedSevereAlertCount,
+      final int expectedWarningAlertCount) {
+    managerVM.invoke("verifyAlertCount", () -> {
+      AlertNotificationListener listener = AlertNotificationListener.getInstance();
 
-
-  @SuppressWarnings("serial")
-  public void setAlertLevel(VM vm1, final String alertLevel) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Set Alert level") {
-
-        public Object call() throws Exception {
-          GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-          ManagementService service = getManagementService();
-          DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-          assertNotNull(bean);
-          bean.changeAlertLevel(alertLevel);
-
-          return null;
-        }
-      });
-
-    }
+      await().until(
+          () -> assertThat(listener.getSevereAlertCount()).isEqualTo(expectedSevereAlertCount));
+      await().until(
+          () -> assertThat(listener.getWarningAlertCount()).isEqualTo(expectedWarningAlertCount));
+    });
   }
 
-  @SuppressWarnings("serial")
-  public void warnLevelAlert(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Warning level Alerts") {
-
-        public Object call() throws Exception {
-          final IgnoredException warnEx =
-              IgnoredException.addIgnoredException(WARNING_LEVEL_MESSAGE);
-          logger.warn(WARNING_LEVEL_MESSAGE);
-          warnEx.remove();
-          return null;
-        }
-      });
-
-    }
+  private void setAlertLevel(final VM managerVM, final String alertLevel) {
+    managerVM.invoke("setAlertLevel", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+      distributedSystemMXBean.changeAlertLevel(alertLevel);
+    });
   }
 
-
-  @SuppressWarnings("serial")
-  public void resetAlertCounts(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Reset Alert Count") {
-
-        public Object call() throws Exception {
-          AlertNotifListener nt = AlertNotifListener.getInstance();
-          nt.resetCount();
-          return null;
-        }
-      });
-
-    }
+  private void generateWarningAlert(final VM anyVM) {
+    anyVM.invoke("generateWarningAlert", () -> {
+      IgnoredException ignoredException =
+          IgnoredException.addIgnoredException(WARNING_LEVEL_MESSAGE);
+      logger.warn(WARNING_LEVEL_MESSAGE);
+      ignoredException.remove();
+    });
   }
 
-  @SuppressWarnings("serial")
-  public void severeLevelAlert(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Severe Level Alert") {
-
-        public Object call() throws Exception {
-          // add expected exception strings
-
-          final IgnoredException severeEx =
-              IgnoredException.addIgnoredException(SEVERE_LEVEL_MESSAGE);
-          logger.fatal(SEVERE_LEVEL_MESSAGE);
-          severeEx.remove();
-          return null;
-        }
-      });
-
-    }
+  private void resetAlertCounts(final VM managerVM) {
+    managerVM.invoke("resetAlertCounts", () -> {
+      AlertNotificationListener listener = AlertNotificationListener.getInstance();
+      listener.resetCount();
+    });
   }
 
-  @SuppressWarnings("serial")
-  public void addAlertListener(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Add Alert Listener") {
-
-        public Object call() throws Exception {
-          GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-          ManagementService service = getManagementService();
-          DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-          AlertNotifListener nt = AlertNotifListener.getInstance();
-          nt.resetCount();
-
-          NotificationFilter notificationFilter = new NotificationFilter() {
-            @Override
-            public boolean isNotificationEnabled(Notification notification) {
-              return notification.getType().equals(JMXNotificationType.SYSTEM_ALERT);
-            }
-
-          };
+  private void generateSevereAlert(final VM anyVM) {
+    anyVM.invoke("generateSevereAlert", () -> {
+      IgnoredException ignoredException =
+          IgnoredException.addIgnoredException(SEVERE_LEVEL_MESSAGE);
+      logger.fatal(SEVERE_LEVEL_MESSAGE);
+      ignoredException.remove();
+    });
+  }
 
-          mbeanServer.addNotificationListener(MBeanJMXAdapter.getDistributedSystemName(), nt,
-              notificationFilter, null);
+  private void addAlertListener(final VM managerVM) {
+    managerVM.invoke("addAlertListener", () -> {
+      AlertNotificationListener listener = AlertNotificationListener.getInstance();
+      listener.resetCount();
 
-          return null;
-        }
-      });
+      NotificationFilter notificationFilter = (Notification notification) -> notification.getType()
+          .equals(JMXNotificationType.SYSTEM_ALERT);
 
-    }
+      ManagementFactory.getPlatformMBeanServer().addNotificationListener(
+          MBeanJMXAdapter.getDistributedSystemName(), listener, notificationFilter, null);
+    });
   }
 
   /**
    * Check aggregate related functions and attributes
-   * 
-   * @param vm1
-   * @throws Exception
    */
-  @SuppressWarnings("serial")
-  public void checkAggregate(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Chech Aggregate Attributes") {
-
-        public Object call() throws Exception {
-          GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-
-          ManagementService service = getManagementService();
-
-          final DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-          assertNotNull(service.getDistributedSystemMXBean());
-
-          Wait.waitForCriterion(new WaitCriterion() {
-            public String description() {
-              return "Waiting All members to intitialize DistributedSystemMBean expect 5 but found "
-                  + bean.getMemberCount();
-            }
-
-            public boolean done() {
-              // including locator
-              if (bean.getMemberCount() == 5) {
-                return true;
-              } else {
-                return false;
-              }
-
-            }
-
-          }, MAX_WAIT, 500, true);
-
-
+  private void verifyDistributedSystemMXBean(final VM managerVM) {
+    managerVM.invoke("verifyDistributedSystemMXBean", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
 
-          final Set<DistributedMember> otherMemberSet =
-              cache.getDistributionManager().getOtherNormalDistributionManagerIds();
-          Iterator<DistributedMember> memberIt = otherMemberSet.iterator();
-          while (memberIt.hasNext()) {
-            DistributedMember member = memberIt.next();
-            LogWriterUtils.getLogWriter().info("JVM Metrics For Member " + member.getId() + ":"
-                + bean.showJVMMetrics(member.getId()));
-            LogWriterUtils.getLogWriter().info("OS Metrics For Member " + member.getId() + ":"
-                + bean.showOSMetrics(member.getId()));
-          }
+      await().until(() -> assertThat(distributedSystemMXBean.getMemberCount()).isEqualTo(5));
 
-          return null;
-        }
-      });
-
-    }
+      Set<DistributedMember> otherMemberSet = this.managementTestRule.getOtherNormalMembers();
+      for (DistributedMember member : otherMemberSet) {
+        // TODO: need assertions? JVMMetrics and OSMetrics
+      }
+    });
   }
 
-  @SuppressWarnings("serial")
-  public void addNotificationListener(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Add Notification Listener") {
-
-        public Object call() throws Exception {
-          GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-          ManagementService service = getManagementService();
-          DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-          assertNotNull(bean);
-          TestDistributedSystemNotif nt = new TestDistributedSystemNotif();
-          mbeanServer.addNotificationListener(MBeanJMXAdapter.getDistributedSystemName(), nt, null,
-              null);
-
-          return null;
-        }
-      });
+  private void addNotificationListener(final VM managerVM) {
+    managerVM.invoke("addNotificationListener", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+      assertThat(distributedSystemMXBean).isNotNull();
 
-    }
+      DistributedSystemNotificationListener listener = new DistributedSystemNotificationListener();
+      ManagementFactory.getPlatformMBeanServer().addNotificationListener(
+          MBeanJMXAdapter.getDistributedSystemName(), listener, null, null);
+    });
   }
 
+  private void shutDownAll(final VM managerVM) {
+    managerVM.invoke("shutDownAll", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+      distributedSystemMXBean.shutDownAllMembers();
 
-
-  @SuppressWarnings("serial")
-  public void shutDownAll(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Shut Down All") {
-
-        public Object call() throws Exception {
-          GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-          ManagementService service = getManagementService();
-          DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-          assertNotNull(service.getDistributedSystemMXBean());
-          bean.shutDownAllMembers();
-          Wait.pause(2000);
-          assertEquals(cache.getDistributedSystem().getAllOtherMembers().size(), 1);
-          return null;
-        }
-      });
-
-    }
+      await().until(() -> assertThat(this.managementTestRule.getOtherNormalMembers()).hasSize(0));
+    });
   }
 
+  private void verifyFetchMemberObjectName(final VM managerVM, final int memberCount) {
+    managerVM.invoke("verifyFetchMemberObjectName", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
 
+      await().until(
+          () -> assertThat(distributedSystemMXBean.listMemberObjectNames()).hasSize(memberCount));
 
-  @SuppressWarnings("serial")
-  public void checkNavigationAPIs(VM vm1) throws Exception {
-    {
-      vm1.invoke(new SerializableCallable("Check Navigation APIS") {
-
-        public Object call() throws Exception {
-          GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-          ManagementService service = getManagementService();
-          final DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-
-          assertNotNull(service.getDistributedSystemMXBean());
-
-          waitForAllMembers(4);
-
-          for (int i = 0; i < bean.listMemberObjectNames().length; i++) {
-            LogWriterUtils.getLogWriter()
-                .info("ObjectNames Of the Mmeber" + bean.listMemberObjectNames()[i]);
-          }
-
-
-          ObjectName thisMemberName = MBeanJMXAdapter.getMemberMBeanName(
-              InternalDistributedSystem.getConnectedInstance().getDistributedMember().getId());
-
-          ObjectName memberName = bean.fetchMemberObjectName(
-              InternalDistributedSystem.getConnectedInstance().getDistributedMember().getId());
-          assertEquals(thisMemberName, memberName);
-
-          return null;
-        }
-      });
-
-    }
+      String memberId = this.managementTestRule.getDistributedMember().getId();
+      ObjectName thisMemberName = MBeanJMXAdapter.getMemberMBeanName(memberId);
+      ObjectName memberName = distributedSystemMXBean.fetchMemberObjectName(memberId);
+      assertThat(memberName).isEqualTo(thisMemberName);
+    });
   }
 
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(2, MINUTES);
+  }
 
-  /**
-   * Notification handler
-   * 
-   * 
-   */
-  private static class TestDistributedSystemNotif implements NotificationListener {
+  private static class DistributedSystemNotificationListener implements NotificationListener {
 
     @Override
-    public void handleNotification(Notification notification, Object handback) {
-      assertNotNull(notification);
+    public void handleNotification(final Notification notification, final Object handback) {
+      assertThat(notification).isNotNull();
     }
-
   }
 
-  /**
-   * Notification handler
-   * 
-   * 
-   */
-  private static class AlertNotifListener implements NotificationListener {
+  private static class AlertNotificationListener implements NotificationListener {
+
+    private static AlertNotificationListener listener = new AlertNotificationListener();
+
+    private int warningAlertCount = 0;
 
-    private static AlertNotifListener listener = new AlertNotifListener();
+    private int severeAlertCount = 0;
 
-    public static AlertNotifListener getInstance() {
+    static AlertNotificationListener getInstance() { // TODO: get rid of singleton
       return listener;
     }
 
-    private int warnigAlertCount = 0;
+    @Override
+    public synchronized void handleNotification(final Notification notification,
+        final Object handback) {
+      assertThat(notification).isNotNull();
 
-    private int severAlertCount = 0;
+      Map<String, String> notificationUserData = (Map<String, String>) notification.getUserData();
 
-    @Override
-    public synchronized void handleNotification(Notification notification, Object handback) {
-      assertNotNull(notification);
-      logger.info("Notification received {}", notification);
-      Map<String, String> notifUserData = (Map<String, String>) notification.getUserData();
-      if (notifUserData.get(JMXNotificationUserData.ALERT_LEVEL).equalsIgnoreCase("warning")) {
-        assertEquals(WARNING_LEVEL_MESSAGE, notification.getMessage());
-        ++warnigAlertCount;
+      if (notificationUserData.get(JMXNotificationUserData.ALERT_LEVEL)
+          .equalsIgnoreCase("warning")) {
+        assertThat(notification.getMessage()).isEqualTo(WARNING_LEVEL_MESSAGE);
+        warningAlertCount++;
       }
-      if (notifUserData.get(JMXNotificationUserData.ALERT_LEVEL).equalsIgnoreCase("severe")) {
-        assertEquals(SEVERE_LEVEL_MESSAGE, notification.getMessage());
-        ++severAlertCount;
+      if (notificationUserData.get(JMXNotificationUserData.ALERT_LEVEL)
+          .equalsIgnoreCase("severe")) {
+        assertThat(notification.getMessage()).isEqualTo(SEVERE_LEVEL_MESSAGE);
+        severeAlertCount++;
       }
     }
 
-    public void resetCount() {
-      warnigAlertCount = 0;
-
-      severAlertCount = 0;
+    void resetCount() {
+      warningAlertCount = 0;
+      severeAlertCount = 0;
     }
 
-    public int getWarnigAlertCount() {
-      return warnigAlertCount;
+    int getWarningAlertCount() {
+      return warningAlertCount;
     }
 
-    public int getseverAlertCount() {
-      return severAlertCount;
+    int getSevereAlertCount() {
+      return severeAlertCount;
     }
-
   }
-
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/JMXMBeanDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/JMXMBeanDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/JMXMBeanDUnitTest.java
index 0feb4c2..0096f0d 100644
--- a/geode-core/src/test/java/org/apache/geode/management/JMXMBeanDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/JMXMBeanDUnitTest.java
@@ -49,7 +49,7 @@ import org.apache.geode.test.junit.categories.FlakyTest;
 import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
 import org.apache.geode.util.test.TestUtil;
 
-public class JMXMBeanDUnitTest extends DistributedTestCase {
+public class JMXMBeanDUnitTest extends DistributedTestCase { // TODO: rename and fix on Mac
 
   private Host host;
   private VM locator;

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/LocatorManagementDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/LocatorManagementDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/LocatorManagementDUnitTest.java
index 205ada5..09f7383 100644
--- a/geode-core/src/test/java/org/apache/geode/management/LocatorManagementDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/LocatorManagementDUnitTest.java
@@ -14,17 +14,8 @@
  */
 package org.apache.geode.management;
 
-import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER;
-import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_HTTP_PORT;
-import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_PORT;
-import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_START;
-import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
-import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL;
-import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
-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.apache.geode.distributed.ConfigurationProperties.*;
+import static org.junit.Assert.*;
 
 import org.apache.geode.distributed.DistributedMember;
 import org.apache.geode.distributed.Locator;


[4/8] geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/QueryDataDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/QueryDataDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/QueryDataDUnitTest.java
index 1773a27..6fd7b98 100644
--- a/geode-core/src/test/java/org/apache/geode/management/QueryDataDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/QueryDataDUnitTest.java
@@ -14,895 +14,739 @@
  */
 package org.apache.geode.management;
 
-import static org.apache.geode.cache.query.Utils.createPortfoliosAndPositions;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.IOException;
+import static com.jayway.jsonpath.matchers.JsonPathMatchers.*;
+import static java.util.concurrent.TimeUnit.*;
+import static org.apache.geode.cache.FixedPartitionAttributes.*;
+import static org.apache.geode.cache.query.Utils.*;
+import static org.apache.geode.management.internal.ManagementConstants.*;
+import static org.apache.geode.management.internal.ManagementStrings.*;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.hamcrest.Matchers.*;
+import static org.junit.Assert.assertThat;
+
+import java.io.Serializable;
 import java.util.ArrayList;
+import java.util.Calendar;
 import java.util.Date;
 import java.util.List;
 import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeoutException;
+
+import javax.management.ObjectName;
+
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
 
 import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.CacheException;
-import org.apache.geode.cache.CacheFactory;
 import org.apache.geode.cache.DataPolicy;
+import org.apache.geode.cache.EntryOperation;
 import org.apache.geode.cache.FixedPartitionAttributes;
 import org.apache.geode.cache.PartitionAttributesFactory;
+import org.apache.geode.cache.PartitionResolver;
 import org.apache.geode.cache.Region;
 import org.apache.geode.cache.RegionFactory;
 import org.apache.geode.cache.RegionShortcut;
-import org.apache.geode.cache.query.data.Portfolio;
-import org.apache.geode.cache.query.dunit.QueryUsingFunctionContextDUnitTest;
-import org.apache.geode.cache30.CacheSerializableRunnable;
+import org.apache.geode.cache.query.data.Portfolio; // TODO
 import org.apache.geode.distributed.DistributedMember;
 import org.apache.geode.internal.cache.BucketRegion;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.internal.cache.PartitionedRegion;
 import org.apache.geode.internal.cache.PartitionedRegionHelper;
-import org.apache.geode.internal.cache.partitioned.fixed.SingleHopQuarterPartitionResolver;
-import org.apache.geode.management.internal.ManagementConstants;
-import org.apache.geode.management.internal.ManagementStrings;
+import org.apache.geode.internal.cache.partitioned.fixed.SingleHopQuarterPartitionResolver; // TODO
 import org.apache.geode.management.internal.SystemManagementService;
 import org.apache.geode.management.internal.beans.BeanUtilFuncs;
 import org.apache.geode.management.internal.cli.json.TypedJson;
 import org.apache.geode.pdx.PdxInstance;
 import org.apache.geode.pdx.PdxInstanceFactory;
 import org.apache.geode.pdx.internal.PdxInstanceFactoryImpl;
-import org.apache.geode.test.dunit.LogWriterUtils;
-import org.apache.geode.test.dunit.SerializableRunnable;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
+import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.dunit.rules.DistributedUseJacksonForJsonPathRule;
 import org.apache.geode.test.junit.categories.DistributedTest;
-import org.apache.geode.test.junit.categories.FlakyTest;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
+import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
 
 /**
+ * Distributed tests for {@link DistributedSystemMXBean#queryData(String, String, int)}.
+ * <p>
  * 
- * 
+ * <pre>
+ * Test Basic Json Strings for Partitioned Regions
+ * Test Basic Json Strings for Replicated Regions
+ * Test for all Region Types
+ * Test for primitive types
+ * Test for Nested Objects
+ * Test for Enums
+ * Test for collections
+ * Test for huge collection
+ * Test PDX types
+ * Test different projects type e.g. SelectResult, normal bean etc..
+ * Test Colocated Regions
+ * Test for Limit ( both row count and Depth)
+ * ORDER by orders
+ * Test all attributes are covered in an complex type
+ * </pre>
  */
-
-// 1) Test Basic Json Strings for Partitioned Regions
-// Test Basic Json Strings for Replicated Regions
-// Test for all Region Types
-// Test for primitive types
-// Test for Nested Objects
-// Test for Enums
-// Test for collections
-// Test for huge collection
-// Test PDX types
-// Test different projects type e.g. SelectResult, normal bean etc..
-// Test Colocated Regions
-// Test for Limit ( both row count and Depth)
-// ORDER by orders
-// Test all attributes are covered in an complex type
-
 @Category(DistributedTest.class)
-public class QueryDataDUnitTest extends ManagementTestBase {
-
-  private static final long serialVersionUID = 1L;
-
-  private static final int MAX_WAIT = 100 * 1000;
-
-  private static final int cntDest = 30;
-
-  private static final int cnt = 0;
-
-  // PR 5 is co-located with 4
-  static String PartitionedRegionName1 = "TestPartitionedRegion1"; // default
-                                                                   // name
-  static String PartitionedRegionName2 = "TestPartitionedRegion2"; // default
-                                                                   // name
-  static String PartitionedRegionName3 = "TestPartitionedRegion3"; // default
-                                                                   // name
-  static String PartitionedRegionName4 = "TestPartitionedRegion4"; // default
-                                                                   // name
-  static String PartitionedRegionName5 = "TestPartitionedRegion5"; // default
-                                                                   // name
-
-
-  static String repRegionName = "TestRepRegion"; // default name
-  static String repRegionName2 = "TestRepRegion2"; // default name
-  static String repRegionName3 = "TestRepRegion3"; // default name
-  static String repRegionName4 = "TestRepRegion4"; // default name
-  static String localRegionName = "TestLocalRegion"; // default name
-
-  public static String[] queries =
-      new String[] {"select * from /" + PartitionedRegionName1 + " where ID>=0",
-          "Select * from /" + PartitionedRegionName1 + " r1, /" + PartitionedRegionName2
-              + " r2 where r1.ID = r2.ID",
-          "Select * from /" + PartitionedRegionName1 + " r1, /" + PartitionedRegionName2
-              + " r2 where r1.ID = r2.ID AND r1.status = r2.status",
-          "Select * from /" + PartitionedRegionName1 + " r1, /" + PartitionedRegionName2 + " r2, /"
-              + PartitionedRegionName3 + " r3 where r1.ID = r2.ID and r2.ID = r3.ID",
-          "Select * from /" + PartitionedRegionName1 + " r1, /" + PartitionedRegionName2 + " r2, /"
-              + PartitionedRegionName3 + " r3  , /" + repRegionName
-              + " r4 where r1.ID = r2.ID and r2.ID = r3.ID and r3.ID = r4.ID",
-          "Select * from /" + PartitionedRegionName4 + " r4 , /" + PartitionedRegionName5
-              + " r5 where r4.ID = r5.ID"};
-
-  public static String[] nonColocatedQueries = new String[] {
-      "Select * from /" + PartitionedRegionName1 + " r1, /" + PartitionedRegionName4
-          + " r4 where r1.ID = r4.ID",
-      "Select * from /" + PartitionedRegionName1 + " r1, /" + PartitionedRegionName4 + " r4 , /"
-          + PartitionedRegionName5 + " r5 where r1.ID = r42.ID and r4.ID = r5.ID"};
-
-  public static String[] queriesForRR =
-      new String[] {"<trace> select * from /" + repRegionName + " where ID>=0",
-          "Select * from /" + repRegionName + " r1, /" + repRegionName2 + " r2 where r1.ID = r2.ID",
-          "select * from /" + repRegionName3 + " where ID>=0"};
-
-  public static String[] queriesForLimit = new String[] {"select * from /" + repRegionName4};
-
-
-  public QueryDataDUnitTest() {
-    super();
-  }
+@SuppressWarnings({"serial", "unused"})
+public class QueryDataDUnitTest implements Serializable {
+
+  private static final int NUM_OF_BUCKETS = 20;
+
+  // PARTITIONED_REGION_NAME5 is co-located with PARTITIONED_REGION_NAME4
+  private static final String PARTITIONED_REGION_NAME1 = "PARTITIONED_REGION_NAME1";
+  private static final String PARTITIONED_REGION_NAME2 = "PARTITIONED_REGION_NAME2";
+  private static final String PARTITIONED_REGION_NAME3 = "PARTITIONED_REGION_NAME3";
+  private static final String PARTITIONED_REGION_NAME4 = "PARTITIONED_REGION_NAME4";
+  private static final String PARTITIONED_REGION_NAME5 = "PARTITIONED_REGION_NAME5";
+
+  private static final String REPLICATE_REGION_NAME1 = "REPLICATE_REGION_NAME1";
+  private static final String REPLICATE_REGION_NAME2 = "REPLICATE_REGION_NAME2";
+  private static final String REPLICATE_REGION_NAME3 = "REPLICATE_REGION_NAME3";
+  private static final String REPLICATE_REGION_NAME4 = "REPLICATE_REGION_NAME4";
+
+  private static final String LOCAL_REGION_NAME = "LOCAL_REGION_NAME";
+
+  private static final String BIG_COLLECTION_ELEMENT_ = "BIG_COLLECTION_ELEMENT_";
+  private static final String BIG_COLLECTION_ = "BIG_COLLECTION_";
+
+  private static final String[] QUERIES =
+      new String[] {"SELECT * FROM /" + PARTITIONED_REGION_NAME1 + " WHERE ID >= 0",
+          "SELECT * FROM /" + PARTITIONED_REGION_NAME1 + " r1, /" + PARTITIONED_REGION_NAME2
+              + " r2 WHERE r1.ID = r2.ID",
+          "SELECT * FROM /" + PARTITIONED_REGION_NAME1 + " r1, /" + PARTITIONED_REGION_NAME2
+              + " r2 WHERE r1.ID = r2.ID AND r1.status = r2.status",
+          "SELECT * FROM /" + PARTITIONED_REGION_NAME1 + " r1, /" + PARTITIONED_REGION_NAME2
+              + " r2, /" + PARTITIONED_REGION_NAME3 + " r3 WHERE r1.ID = r2.ID AND r2.ID = r3.ID",
+          "SELECT * FROM /" + PARTITIONED_REGION_NAME1 + " r1, /" + PARTITIONED_REGION_NAME2
+              + " r2, /" + PARTITIONED_REGION_NAME3 + " r3, /" + REPLICATE_REGION_NAME1
+              + " r4 WHERE r1.ID = r2.ID AND r2.ID = r3.ID AND r3.ID = r4.ID",
+          "SELECT * FROM /" + PARTITIONED_REGION_NAME4 + " r4, /" + PARTITIONED_REGION_NAME5
+              + " r5 WHERE r4.ID = r5.ID"};
+
+  private static final String[] QUERIES_FOR_REPLICATED =
+      new String[] {"<TRACE> SELECT * FROM /" + REPLICATE_REGION_NAME1 + " WHERE ID >= 0",
+          "SELECT * FROM /" + REPLICATE_REGION_NAME1 + " r1, /" + REPLICATE_REGION_NAME2
+              + " r2 WHERE r1.ID = r2.ID",
+          "SELECT * FROM /" + REPLICATE_REGION_NAME3 + " WHERE ID >= 0"};
+
+  private static final String[] QUERIES_FOR_LIMIT =
+      new String[] {"SELECT * FROM /" + REPLICATE_REGION_NAME4};
+
+  private DistributedMember member1;
+  private DistributedMember member2;
+  private DistributedMember member3;
+
+  @Manager
+  private VM managerVM;
+
+  @Member
+  private VM[] memberVMs;
+
+  @Rule
+  public DistributedUseJacksonForJsonPathRule useJacksonForJsonPathRule =
+      new DistributedUseJacksonForJsonPathRule();
+
+  @Rule
+  public ManagementTestRule managementTestRule =
+      ManagementTestRule.builder().managersFirst(false).start(true).build();
+
+  @Rule
+  public SerializableTestName testName = new SerializableTestName();
+
+  @Before
+  public void before() throws Exception {
+    this.member1 = this.managementTestRule.getDistributedMember(this.memberVMs[0]);
+    this.member2 = this.managementTestRule.getDistributedMember(this.memberVMs[1]);
+    this.member3 = this.managementTestRule.getDistributedMember(this.memberVMs[2]);
 
-  @Override
-  protected final void postSetUpManagementTestBase() throws Exception {
-    initManagement(false);
-  }
-
-  private void initCommonRegions() {
     createRegionsInNodes();
-    fillValuesInRegions();
+    generateValuesInRegions();
   }
 
-  /**
-   * This function puts portfolio objects into the created Region (PR or Local) *
-   */
-  public CacheSerializableRunnable getCacheSerializableRunnableForPRPuts(final String regionName,
-      final Object[] portfolio, final int from, final int to) {
-    SerializableRunnable puts = new CacheSerializableRunnable("Region Puts") {
-      @Override
-      public void run2() throws CacheException {
-        Cache cache = CacheFactory.getAnyInstance();
-        Region region = cache.getRegion(regionName);
-        for (int j = from; j < to; j++)
-          region.put(new Integer(j), portfolio[j]);
-        LogWriterUtils.getLogWriter().info(
-            "PRQueryDUnitHelper#getCacheSerializableRunnableForPRPuts: Inserted Portfolio data on Region "
-                + regionName);
-      }
-    };
-    return (CacheSerializableRunnable) puts;
-  }
-
-  /**
-   * This function puts PDX objects into the created Region (REPLICATED) *
-   */
-  public CacheSerializableRunnable getCacheSerializableRunnableForPDXPuts(final String regionName) {
-    SerializableRunnable puts = new CacheSerializableRunnable("Region Puts") {
-      @Override
-      public void run2() throws CacheException {
-        putPdxInstances(regionName);
-
-      }
-    };
-    return (CacheSerializableRunnable) puts;
-  }
-
-  /**
-   * This function puts big collections to created Region (REPLICATED) *
-   */
-  public CacheSerializableRunnable getCacheSerializableRunnableForBigCollPuts(
-      final String regionName) {
-    SerializableRunnable bigPuts = new CacheSerializableRunnable("Big Coll Puts") {
-      @Override
-      public void run2() throws CacheException {
-        putBigInstances(regionName);
-
-      }
-    };
-    return (CacheSerializableRunnable) bigPuts;
-  }
-
-  public void fillValuesInRegions() {
-    // Create common Portflios and NewPortfolios
-    final Portfolio[] portfolio = createPortfoliosAndPositions(cntDest);
-
-    // Fill local region
-    managedNode1
-        .invoke(getCacheSerializableRunnableForPRPuts(localRegionName, portfolio, cnt, cntDest));
-
-    // Fill replicated region
-    managedNode1
-        .invoke(getCacheSerializableRunnableForPRPuts(repRegionName, portfolio, cnt, cntDest));
-    managedNode2
-        .invoke(getCacheSerializableRunnableForPRPuts(repRegionName2, portfolio, cnt, cntDest));
-
-    // Fill Partition Region
-    managedNode1.invoke(
-        getCacheSerializableRunnableForPRPuts(PartitionedRegionName1, portfolio, cnt, cntDest));
-    managedNode1.invoke(
-        getCacheSerializableRunnableForPRPuts(PartitionedRegionName2, portfolio, cnt, cntDest));
-    managedNode1.invoke(
-        getCacheSerializableRunnableForPRPuts(PartitionedRegionName3, portfolio, cnt, cntDest));
-    managedNode1.invoke(
-        getCacheSerializableRunnableForPRPuts(PartitionedRegionName4, portfolio, cnt, cntDest));
-    managedNode1.invoke(
-        getCacheSerializableRunnableForPRPuts(PartitionedRegionName5, portfolio, cnt, cntDest));
-
-    managedNode1.invoke(getCacheSerializableRunnableForPDXPuts(repRegionName3));
-
-  }
-
-  public void putPdxInstances(String regionName) throws CacheException {
-    PdxInstanceFactory pf = PdxInstanceFactoryImpl.newCreator("Portfolio", false);
-    Region r = getCache().getRegion(regionName);
-    pf.writeInt("ID", 111);
-    pf.writeString("status", "active");
-    pf.writeString("secId", "IBM");
-    PdxInstance pi = pf.create();
-    r.put("IBM", pi);
-
-    pf = PdxInstanceFactoryImpl.newCreator("Portfolio", false);
-    pf.writeInt("ID", 222);
-    pf.writeString("status", "inactive");
-    pf.writeString("secId", "YHOO");
-    pi = pf.create();
-    r.put("YHOO", pi);
-
-    pf = PdxInstanceFactoryImpl.newCreator("Portfolio", false);
-    pf.writeInt("ID", 333);
-    pf.writeString("status", "active");
-    pf.writeString("secId", "GOOGL");
-    pi = pf.create();
-    r.put("GOOGL", pi);
-
-    pf = PdxInstanceFactoryImpl.newCreator("Portfolio", false);
-    pf.writeInt("ID", 111);
-    pf.writeString("status", "inactive");
-    pf.writeString("secId", "VMW");
-    pi = pf.create();
-    r.put("VMW", pi);
-  }
-
-  public void putBigInstances(String regionName) throws CacheException {
-    Region r = getCache().getRegion(regionName);
-
-    for (int i = 0; i < 1200; i++) {
-      List<String> bigColl1 = new ArrayList<String>();
-      for (int j = 0; j < 200; j++) {
-        bigColl1.add("BigColl_1_ElemenNo_" + j);
-      }
-      r.put("BigColl_1_" + i, bigColl1);
-    }
-
-  }
-
-  private void createRegionsInNodes() {
-
-    // Create local Region on servers
-    managedNode1.invoke(() -> QueryUsingFunctionContextDUnitTest.createLocalRegion());
-
-    // Create ReplicatedRegion on servers
-    managedNode1.invoke(() -> QueryUsingFunctionContextDUnitTest.createReplicatedRegion());
-    managedNode2.invoke(() -> QueryUsingFunctionContextDUnitTest.createReplicatedRegion());
-    managedNode3.invoke(() -> QueryUsingFunctionContextDUnitTest.createReplicatedRegion());
-    try {
-      this.createDistributedRegion(managedNode2, repRegionName2);
-      this.createDistributedRegion(managedNode1, repRegionName3);
-      this.createDistributedRegion(managedNode1, repRegionName4);
-    } catch (Exception e1) {
-      fail("Test Failed while creating region " + e1.getMessage());
-    }
-
-    // Create two colocated PartitionedRegions On Servers.
-    managedNode1.invoke(() -> QueryUsingFunctionContextDUnitTest.createColocatedPR());
-    managedNode2.invoke(() -> QueryUsingFunctionContextDUnitTest.createColocatedPR());
-    managedNode3.invoke(() -> QueryUsingFunctionContextDUnitTest.createColocatedPR());
-
-    this.managingNode
-        .invoke(new SerializableRunnable("Wait for all Region Proxies to get replicated") {
-
-          public void run() {
-            Cache cache = getCache();
-            SystemManagementService service = (SystemManagementService) getManagementService();
-            DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-
-            try {
-              MBeanUtil.getDistributedRegionMbean("/" + PartitionedRegionName1, 3);
-              MBeanUtil.getDistributedRegionMbean("/" + PartitionedRegionName2, 3);
-              MBeanUtil.getDistributedRegionMbean("/" + PartitionedRegionName3, 3);
-              MBeanUtil.getDistributedRegionMbean("/" + PartitionedRegionName4, 3);
-              MBeanUtil.getDistributedRegionMbean("/" + PartitionedRegionName5, 3);
-              MBeanUtil.getDistributedRegionMbean("/" + repRegionName, 3);
-              MBeanUtil.getDistributedRegionMbean("/" + repRegionName2, 1);
-              MBeanUtil.getDistributedRegionMbean("/" + repRegionName3, 1);
-              MBeanUtil.getDistributedRegionMbean("/" + repRegionName4, 1);
-            } catch (Exception e) {
-              fail("Region proxies not replicated in time");
-            }
-          }
-        });
-
-  }
-
-  // disabled for bug 49698, serialization problems introduced by r44615
   @Test
   public void testQueryOnPartitionedRegion() throws Exception {
-
-    final DistributedMember member1 = getMember(managedNode1);
-    final DistributedMember member2 = getMember(managedNode2);
-    final DistributedMember member3 = getMember(managedNode3);
-
-    initCommonRegions();
-
-
-    this.managingNode.invoke(new SerializableRunnable("testQueryOnPartitionedRegion") {
-
-      public void run() {
-        Cache cache = getCache();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-
-        assertNotNull(bean);
-
-        try {
-          for (int i = 0; i < queries.length; i++) {
-            String jsonString = null;
-            if (i == 0) {
-              jsonString = bean.queryData(queries[i], null, 10);
-              if (jsonString.contains("result") && !jsonString.contains("No Data Found")) {
-
-                // getLogWriter().info("testQueryOnPartitionedRegion" + queries[i] + " is = " +
-                // jsonString);
-                JSONObject jsonObj = new JSONObject(jsonString);
-              } else {
-                fail("Query On Cluster should have result");
-              }
-            } else {
-              jsonString = bean.queryData(queries[i], member1.getId(), 10);
-              if (jsonString.contains("member")) {
-                JSONObject jsonObj = new JSONObject(jsonString);
-                // getLogWriter().info("testQueryOnPartitionedRegion" + queries[i] + " is = " +
-                // jsonString);
-              } else {
-                fail("Query On Member should have member");
-              }
-            }
-
-
-
-          }
-        } catch (JSONException e) {
-          e.printStackTrace();
-          fail(e.getMessage());
-        } catch (Exception e) {
-          e.printStackTrace();
-          fail(e.getMessage());
-        }
+    this.managerVM.invoke(this.testName.getMethodName(), () -> {
+      DistributedSystemMXBean distributedSystemMXBean =
+          this.managementTestRule.getSystemManagementService().getDistributedSystemMXBean();
+
+      String jsonString = distributedSystemMXBean.queryData(QUERIES[0], null, 10);
+      assertThat(jsonString).contains("result").doesNotContain("No Data Found");
+
+      for (int i = 0; i < QUERIES.length; i++) {
+        jsonString = distributedSystemMXBean.queryData(QUERIES[i], member1.getId(), 10);
+        assertThat(jsonString).contains("result");
+        assertThat(jsonString).contains("member");
+        assertThat("QUERIES[" + i + "]", jsonString, isJson(withJsonPath("$..result", anything())));
+
+        // TODO: better assertions
+        // assertThat("QUERIES[" + i + "]", result,
+        // isJson(withJsonPath("$..member",
+        // equalTo(JsonPath.compile(result)))));
+        // //equalTo(new JSONObject().put(String.class.getName(), member1.getId())))));
+        // System.out.println(JsonPath.read(jsonString, "$.result.*"));
+        // System.out.println(JsonPath.read(jsonString, "$['result']['member']"));
+
+        verifyJsonIsValid(jsonString);
       }
     });
   }
 
   @Test
   public void testQueryOnReplicatedRegion() throws Exception {
+    this.managerVM.invoke(this.testName.getMethodName(), () -> {
+      DistributedSystemMXBean distributedSystemMXBean =
+          this.managementTestRule.getSystemManagementService().getDistributedSystemMXBean();
 
+      String jsonString = distributedSystemMXBean.queryData(QUERIES_FOR_REPLICATED[0], null, 10);
+      assertThat(jsonString).contains("result").doesNotContain("No Data Found");
 
-    initCommonRegions();
-
-
-    this.managingNode.invoke(new SerializableRunnable("Query Test For REPL1") {
-
-
-      public void run() {
-        Cache cache = getCache();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        assertNotNull(bean);
-
-        try {
-          for (int i = 0; i < queriesForRR.length; i++) {
-            String jsonString1 = null;
-            if (i == 0) {
-              jsonString1 = bean.queryData(queriesForRR[i], null, 10);
-              if (jsonString1.contains("result") && !jsonString1.contains("No Data Found")) {
-                JSONObject jsonObj = new JSONObject(jsonString1);
-              } else {
-                fail("Query On Cluster should have result");
-              }
-            } else {
-              jsonString1 = bean.queryData(queriesForRR[i], null, 10);
-              if (jsonString1.contains("result")) {
-                JSONObject jsonObj = new JSONObject(jsonString1);
-              } else {
-                LogWriterUtils.getLogWriter()
-                    .info("Failed Test String" + queriesForRR[i] + " is = " + jsonString1);
-                fail("Join on Replicated did not work.");
-              }
-            }
-          }
-
-        } catch (JSONException e) {
-          fail(e.getMessage());
-        } catch (IOException e) {
-          fail(e.getMessage());
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
+      for (int i = 0; i < QUERIES_FOR_REPLICATED.length; i++) {
+        assertThat(jsonString).contains("result");
+        verifyJsonIsValid(jsonString);
       }
     });
   }
 
-  @Category(FlakyTest.class) // GEODE-1539
   @Test
   public void testMemberWise() throws Exception {
+    this.managerVM.invoke(this.testName.getMethodName(), () -> {
+      DistributedSystemMXBean distributedSystemMXBean =
+          this.managementTestRule.getSystemManagementService().getDistributedSystemMXBean();
 
-    final DistributedMember member1 = getMember(managedNode1);
-    final DistributedMember member2 = getMember(managedNode2);
-
-
-    initCommonRegions();
+      byte[] bytes = distributedSystemMXBean.queryDataForCompressedResult(QUERIES_FOR_REPLICATED[0],
+          member1.getId() + "," + member2.getId(), 2);
+      String jsonString = BeanUtilFuncs.decompress(bytes);
 
-
-    this.managingNode.invoke(new SerializableRunnable("testMemberWise") {
-
-      public void run() {
-        Cache cache = getCache();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        assertNotNull(bean);
-
-        try {
-          byte[] bytes = bean.queryDataForCompressedResult(queriesForRR[0],
-              member1.getId() + "," + member2.getId(), 2);
-          String jsonString = BeanUtilFuncs.decompress(bytes);
-          JSONObject jsonObj = new JSONObject(jsonString);
-          // String memberID = (String)jsonObj.get("member");
-
-          // getLogWriter().info("testMemberWise " + queriesForRR[2] + " is = " + jsonString);
-
-        } catch (JSONException e) {
-          fail(e.getMessage());
-        } catch (IOException e) {
-          fail(e.getMessage());
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
-      }
+      verifyJsonIsValid(jsonString);
     });
   }
 
-
-
   @Test
   public void testLimitForQuery() throws Exception {
+    this.memberVMs[0].invoke("putBigInstances", () -> putBigInstances(REPLICATE_REGION_NAME4));
 
-    initCommonRegions();
-    managedNode1.invoke(getCacheSerializableRunnableForBigCollPuts(repRegionName4));
+    this.managerVM.invoke(this.testName.getMethodName(), () -> {
+      DistributedSystemMXBean distributedSystemMXBean =
+          this.managementTestRule.getSystemManagementService().getDistributedSystemMXBean();
 
-    managingNode.invoke(new SerializableRunnable("testLimitForQuery") {
-      public void run() {
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        assertNotNull(bean);
+      // Query With Default values
+      assertThat(distributedSystemMXBean.getQueryCollectionsDepth())
+          .isEqualTo(TypedJson.DEFAULT_COLLECTION_ELEMENT_LIMIT);
+      assertThat(distributedSystemMXBean.getQueryResultSetLimit()).isEqualTo(DEFAULT_QUERY_LIMIT);
 
-        try {
+      String jsonString = distributedSystemMXBean.queryData(QUERIES_FOR_LIMIT[0], null, 0);
 
-          // Query With Default values
-          assertEquals(TypedJson.DEFAULT_COLLECTION_ELEMENT_LIMIT, bean.getQueryCollectionsDepth());
-          assertEquals(ManagementConstants.DEFAULT_QUERY_LIMIT, bean.getQueryResultSetLimit());
+      verifyJsonIsValid(jsonString);
+      assertThat(jsonString).contains("result").doesNotContain("No Data Found");
+      assertThat(jsonString).contains(BIG_COLLECTION_ELEMENT_);
 
-          String jsonString1 = bean.queryData(queriesForLimit[0], null, 0);
-          if (jsonString1.contains("result") && !jsonString1.contains("No Data Found")) {
-            JSONObject jsonObj = new JSONObject(jsonString1);
-            assertTrue(jsonString1.contains("BigColl_1_ElemenNo_"));
-            JSONArray arr = jsonObj.getJSONArray("result");
-            assertEquals(ManagementConstants.DEFAULT_QUERY_LIMIT, arr.length());
-            // Get the first element
+      JSONObject jsonObject = new JSONObject(jsonString);
+      JSONArray jsonArray = jsonObject.getJSONArray("result");
+      assertThat(jsonArray.length()).isEqualTo(DEFAULT_QUERY_LIMIT);
 
-            JSONArray array1 = (JSONArray) arr.getJSONArray(0);
-            // Get the ObjectValue
+      // Get the first element
+      JSONArray jsonArray1 = jsonArray.getJSONArray(0);
 
-            JSONObject collectionObject = (JSONObject) array1.get(1);
-            assertEquals(100, collectionObject.length());
+      // Get the ObjectValue
+      JSONObject collectionObject = (JSONObject) jsonArray1.get(1);
+      assertThat(collectionObject.length()).isEqualTo(100);
 
-          } else {
-            fail("Query On Cluster should have result");
-          }
+      // Query With Override Values
+      int newQueryCollectionDepth = 150;
+      int newQueryResultSetLimit = 500;
 
-          // Query With Ovverride Values
+      distributedSystemMXBean.setQueryCollectionsDepth(newQueryCollectionDepth);
+      distributedSystemMXBean.setQueryResultSetLimit(newQueryResultSetLimit);
 
-          int newQueryCollectionDepth = 150;
-          int newQueryResultSetLimit = 500;
-          bean.setQueryCollectionsDepth(newQueryCollectionDepth);
-          bean.setQueryResultSetLimit(newQueryResultSetLimit);
+      assertThat(distributedSystemMXBean.getQueryCollectionsDepth())
+          .isEqualTo(newQueryCollectionDepth);
+      assertThat(distributedSystemMXBean.getQueryResultSetLimit())
+          .isEqualTo(newQueryResultSetLimit);
 
-          assertEquals(newQueryCollectionDepth, bean.getQueryCollectionsDepth());
-          assertEquals(newQueryResultSetLimit, bean.getQueryResultSetLimit());
+      jsonString = distributedSystemMXBean.queryData(QUERIES_FOR_LIMIT[0], null, 0);
 
-          jsonString1 = bean.queryData(queriesForLimit[0], null, 0);
-          if (jsonString1.contains("result") && !jsonString1.contains("No Data Found")) {
-            JSONObject jsonObj = new JSONObject(jsonString1);
-            assertTrue(jsonString1.contains("BigColl_1_ElemenNo_"));
-            JSONArray arr = jsonObj.getJSONArray("result");
-            assertEquals(newQueryResultSetLimit, arr.length());
-            // Get the first element
+      verifyJsonIsValid(jsonString);
+      assertThat(jsonString).contains("result").doesNotContain("No Data Found");
 
-            JSONArray array1 = (JSONArray) arr.getJSONArray(0);
-            // Get the ObjectValue
+      jsonObject = new JSONObject(jsonString);
+      assertThat(jsonString).contains(BIG_COLLECTION_ELEMENT_);
 
-            JSONObject collectionObject = (JSONObject) array1.get(1);
-            assertEquals(newQueryCollectionDepth, collectionObject.length());
+      jsonArray = jsonObject.getJSONArray("result");
+      assertThat(jsonArray.length()).isEqualTo(newQueryResultSetLimit);
 
-          } else {
-            fail("Query On Cluster should have result");
-          }
+      // Get the first element
+      jsonArray1 = jsonArray.getJSONArray(0);
 
-        } catch (JSONException e) {
-          fail(e.getMessage());
-        } catch (IOException e) {
-          fail(e.getMessage());
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
-
-      }
+      // Get the ObjectValue
+      collectionObject = (JSONObject) jsonArray1.get(1);
+      assertThat(collectionObject.length()).isEqualTo(newQueryCollectionDepth);
     });
   }
 
   @Test
   public void testErrors() throws Exception {
-
-    final DistributedMember member1 = getMember(managedNode1);
-    final DistributedMember member2 = getMember(managedNode2);
-    final DistributedMember member3 = getMember(managedNode3);
-
-    initCommonRegions();
-
-    this.managingNode.invoke(new SerializableRunnable("Test Error") {
-      public void run() {
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        assertNotNull(bean);
-
-        try {
-          Cache cache = getCache();
-          try {
-            String message = bean.queryData("Select * from TestPartitionedRegion1", null, 2);
-
-            JSONObject jsonObject = new JSONObject();
-            jsonObject.put("message", ManagementStrings.QUERY__MSG__INVALID_QUERY
-                .toLocalizedString("Region mentioned in query probably missing /"));
-            String expectedMessage = jsonObject.toString();
-            assertEquals(expectedMessage, message);
-
-          } catch (Exception e) {
-            fail(e.getLocalizedMessage());
-          }
-
-          try {
-            String query =
-                "Select * from /PartitionedRegionName9 r1, PartitionedRegionName2 r2 where r1.ID = r2.ID";
-            String message = bean.queryData(query, null, 2);
-            JSONObject jsonObject = new JSONObject();
-            jsonObject.put("message", ManagementStrings.QUERY__MSG__REGIONS_NOT_FOUND
-                .toLocalizedString("/PartitionedRegionName9"));
-            String expectedMessage = jsonObject.toString();
-            assertEquals(expectedMessage, message);
-          } catch (Exception e) {
-            fail(e.getLocalizedMessage());
-
-          }
-
-          final String testTemp = "testTemp";
-          try {
-            RegionFactory rf = cache.createRegionFactory(RegionShortcut.REPLICATE);
-
-            rf.create(testTemp);
-            String query = "Select * from /" + testTemp;
-
-            String message = bean.queryData(query, member1.getId(), 2);
-
-            JSONObject jsonObject = new JSONObject();
-            jsonObject.put("message", ManagementStrings.QUERY__MSG__REGIONS_NOT_FOUND_ON_MEMBERS
-                .toLocalizedString("/" + testTemp));
-            String expectedMessage = jsonObject.toString();
-            assertEquals(expectedMessage, message);
-          } catch (Exception e) {
-            fail(e.getLocalizedMessage());
-          }
-
-          try {
-            String query = queries[1];
-            String message = bean.queryData(query, null, 2);
-
-            JSONObject jsonObject = new JSONObject();
-            jsonObject.put("message", ManagementStrings.QUERY__MSG__JOIN_OP_EX.toLocalizedString());
-            String expectedMessage = jsonObject.toString();
-
-            assertEquals(expectedMessage, message);
-          } catch (Exception e) {
-            fail(e.getLocalizedMessage());
-          }
-
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
-
-      }
+    this.managerVM.invoke(this.testName.getMethodName(), () -> {
+      DistributedSystemMXBean distributedSystemMXBean =
+          this.managementTestRule.getSystemManagementService().getDistributedSystemMXBean();
+
+      String invalidQuery = "SELECT * FROM " + PARTITIONED_REGION_NAME1;
+      String invalidQueryResult = distributedSystemMXBean.queryData(invalidQuery, null, 2);
+      assertThat(invalidQueryResult,
+          isJson(withJsonPath("$.message", equalTo(QUERY__MSG__INVALID_QUERY
+              .toLocalizedString("Region mentioned in query probably missing /")))));
+
+      String nonexistentRegionName = this.testName.getMethodName() + "_NONEXISTENT_REGION";
+      String regionsNotFoundQuery = "SELECT * FROM /" + nonexistentRegionName
+          + " r1, PARTITIONED_REGION_NAME2 r2 WHERE r1.ID = r2.ID";
+      String regionsNotFoundResult =
+          distributedSystemMXBean.queryData(regionsNotFoundQuery, null, 2);
+      assertThat(regionsNotFoundResult, isJson(withJsonPath("$.message",
+          equalTo(QUERY__MSG__REGIONS_NOT_FOUND.toLocalizedString("/" + nonexistentRegionName)))));
+
+      String regionName = this.testName.getMethodName() + "_REGION";
+      String regionsNotFoundOnMembersQuery = "SELECT * FROM /" + regionName;
+
+      RegionFactory regionFactory =
+          this.managementTestRule.getCache().createRegionFactory(RegionShortcut.REPLICATE);
+      regionFactory.create(regionName);
+
+      String regionsNotFoundOnMembersResult =
+          distributedSystemMXBean.queryData(regionsNotFoundOnMembersQuery, member1.getId(), 2);
+      assertThat(regionsNotFoundOnMembersResult, isJson(withJsonPath("$.message",
+          equalTo(QUERY__MSG__REGIONS_NOT_FOUND_ON_MEMBERS.toLocalizedString("/" + regionName)))));
+
+      String joinMissingMembersQuery = QUERIES[1];
+      String joinMissingMembersResult =
+          distributedSystemMXBean.queryData(joinMissingMembersQuery, null, 2);
+      assertThat(joinMissingMembersResult,
+          isJson(withJsonPath("$.message", equalTo(QUERY__MSG__JOIN_OP_EX.toLocalizedString()))));
     });
   }
 
   @Test
   public void testNormalRegions() throws Exception {
-
-    final DistributedMember member1 = getMember(managedNode1);
-    final DistributedMember member2 = getMember(managedNode2);
-    final DistributedMember member3 = getMember(managedNode3);
-    initCommonRegions();
-
-    this.managingNode.invoke(new SerializableRunnable("Test Error") {
-      public void run() {
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        assertNotNull(bean);
-        final String testNormal = "testNormal";
-        final String testTemp = "testTemp";
-
-        final String testSNormal = "testSNormal"; // to Reverse order of regions while getting
-                                                  // Random region in QueryDataFunction
-        final String testATemp = "testATemp";
-
-        try {
-          Cache cache = getCache();
-          RegionFactory rf = cache.createRegionFactory(RegionShortcut.LOCAL_HEAP_LRU);
-          rf.create(testNormal);
-          rf.create(testSNormal);
-
-
-          Region region = cache.getRegion("/" + testNormal);
-          assertTrue(region.getAttributes().getDataPolicy() == DataPolicy.NORMAL);
-
-          RegionFactory rf1 = cache.createRegionFactory(RegionShortcut.REPLICATE);
-          rf1.create(testTemp);
-          rf1.create(testATemp);
-          String query1 = "Select * from /testTemp r1,/testNormal r2 where r1.ID = r2.ID";
-          String query2 = "Select * from /testSNormal r1,/testATemp r2 where r1.ID = r2.ID";
-          String query3 = "Select * from /testSNormal";
-
-          try {
-
-            bean.queryDataForCompressedResult(query1, null, 2);
-            bean.queryDataForCompressedResult(query2, null, 2);
-            bean.queryDataForCompressedResult(query3, null, 2);
-          } catch (Exception e) {
-            e.printStackTrace();
-          }
-
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
-
-      }
+    this.managerVM.invoke(this.testName.getMethodName(), () -> {
+      DistributedSystemMXBean distributedSystemMXBean =
+          this.managementTestRule.getSystemManagementService().getDistributedSystemMXBean();
+
+      String normalRegionName1 = this.testName.getMethodName() + "_NORMAL_REGION_1";
+      String tempRegionName1 = this.testName.getMethodName() + "_TEMP_REGION_1";
+
+      String normalRegionName2 = this.testName.getMethodName() + "_NORMAL_REGION_2"; // to Reverse
+                                                                                     // order of
+                                                                                     // regions
+                                                                                     // while
+                                                                                     // getting
+                                                                                     // Random
+                                                                                     // region in
+                                                                                     // QueryDataFunction
+                                                                                     // [?]
+      String tempRegionName2 = this.testName.getMethodName() + "_TEMP_REGION_2";
+
+      Cache cache = this.managementTestRule.getCache();
+
+      RegionFactory regionFactory = cache.createRegionFactory(RegionShortcut.LOCAL_HEAP_LRU);
+      regionFactory.create(normalRegionName1);
+      regionFactory.create(normalRegionName2);
+
+      Region region = cache.getRegion("/" + normalRegionName1);
+      assertThat(region.getAttributes().getDataPolicy()).isEqualTo(DataPolicy.NORMAL);
+
+      RegionFactory regionFactory1 = cache.createRegionFactory(RegionShortcut.REPLICATE);
+      regionFactory1.create(tempRegionName1);
+      regionFactory1.create(tempRegionName2);
+
+      String query1 = "SELECT * FROM /" + tempRegionName1 + " r1, /" + normalRegionName1
+          + " r2 WHERE r1.ID = r2.ID";
+      String query2 = "SELECT * FROM /" + normalRegionName2 + " r1, /" + tempRegionName2
+          + " r2 WHERE r1.ID = r2.ID";
+      String query3 = "SELECT * FROM /" + normalRegionName2;
+
+      distributedSystemMXBean.queryDataForCompressedResult(query1, null, 2);
+      distributedSystemMXBean.queryDataForCompressedResult(query2, null, 2);
+      distributedSystemMXBean.queryDataForCompressedResult(query3, null, 2);
+
+      // TODO: assert results of queryDataForCompressedResult?
     });
   }
 
   @Test
   public void testRegionsLocalDataSet() throws Exception {
+    String partitionedRegionName = this.testName.getMethodName() + "_PARTITIONED_REGION";
+
+    String[] values1 = new String[] {"val1", "val2", "val3"};
+    String[] values2 = new String[] {"val4", "val5", "val6"};
 
-    final DistributedMember member1 = getMember(managedNode1);
-    final DistributedMember member2 = getMember(managedNode2);
-    final DistributedMember member3 = getMember(managedNode3);
+    this.memberVMs[0].invoke(this.testName.getMethodName() + " Create Region", () -> {
+      PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory();
+      partitionAttributesFactory.setRedundantCopies(2).setTotalNumBuckets(12);
 
-    final String PartitionedRegionName6 = "LocalDataSetTest";
+      List<FixedPartitionAttributes> fixedPartitionAttributesList = createFixedPartitionList(1);
+      for (FixedPartitionAttributes fixedPartitionAttributes : fixedPartitionAttributesList) {
+        partitionAttributesFactory.addFixedPartitionAttributes(fixedPartitionAttributes);
+      }
+      partitionAttributesFactory.setPartitionResolver(new SingleHopQuarterPartitionResolver());
 
-    final String[] valArray1 = new String[] {"val1", "val2", "val3"};
-    final String[] valArray2 = new String[] {"val4", "val5", "val6"};
-    this.managedNode1.invoke(new SerializableRunnable("testRegionsLocalDataSet:Create Region") {
-      public void run() {
-        try {
+      RegionFactory regionFactory =
+          this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION)
+              .setPartitionAttributes(partitionAttributesFactory.create());
+      Region region = regionFactory.create(partitionedRegionName);
 
-          Cache cache = getCache();
-          PartitionAttributesFactory paf = new PartitionAttributesFactory();
+      for (int i = 0; i < values1.length; i++) {
+        region.put(getDate(2013, 1, i + 5), values1[i]);
+      }
+    });
 
-          paf.setRedundantCopies(2).setTotalNumBuckets(12);
+    this.memberVMs[1].invoke(this.testName.getMethodName() + " Create Region", () -> {
+      PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory();
+      partitionAttributesFactory.setRedundantCopies(2).setTotalNumBuckets(12);
 
-          List<FixedPartitionAttributes> fpaList = createFixedPartitionList(1);
-          for (FixedPartitionAttributes fpa : fpaList) {
-            paf.addFixedPartitionAttributes(fpa);
-          }
-          paf.setPartitionResolver(new SingleHopQuarterPartitionResolver());
+      List<FixedPartitionAttributes> fixedPartitionAttributesList = createFixedPartitionList(2);
+      for (FixedPartitionAttributes fixedPartitionAttributes : fixedPartitionAttributesList) {
+        partitionAttributesFactory.addFixedPartitionAttributes(fixedPartitionAttributes);
+      }
+      partitionAttributesFactory.setPartitionResolver(new SingleHopQuarterPartitionResolver());
 
-          RegionFactory rf = cache.createRegionFactory(RegionShortcut.PARTITION)
-              .setPartitionAttributes(paf.create());
+      RegionFactory regionFactory =
+          this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION)
+              .setPartitionAttributes(partitionAttributesFactory.create());
+      Region region = regionFactory.create(partitionedRegionName);
 
-          Region r = rf.create(PartitionedRegionName6);
+      for (int i = 0; i < values2.length; i++) {
+        region.put(getDate(2013, 5, i + 5), values2[i]);
+      }
+    });
 
-          for (int i = 0; i < valArray1.length; i++) {
-            r.put(new Date(2013, 1, i + 5), valArray1[i]);
-          }
-        } catch (Exception e) {
-          e.printStackTrace();
-          fail(e.getMessage());
-        }
+    this.memberVMs[2].invoke(this.testName.getMethodName() + " Create Region", () -> {
+      PartitionAttributesFactory partitionAttributesFactory = new PartitionAttributesFactory();
+      partitionAttributesFactory.setRedundantCopies(2).setTotalNumBuckets(12);
 
+      List<FixedPartitionAttributes> fixedPartitionAttributesList = createFixedPartitionList(3);
+      for (FixedPartitionAttributes fixedPartitionAttributes : fixedPartitionAttributesList) {
+        partitionAttributesFactory.addFixedPartitionAttributes(fixedPartitionAttributes);
       }
+      partitionAttributesFactory.setPartitionResolver(new SingleHopQuarterPartitionResolver());
+
+      RegionFactory regionFactory =
+          this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION)
+              .setPartitionAttributes(partitionAttributesFactory.create());
+      regionFactory.create(partitionedRegionName);
     });
 
-    this.managedNode2.invoke(new SerializableRunnable("testRegionsLocalDataSet: Create Region") {
-      public void run() {
-        try {
+    final List<String> member1RealData =
+        this.memberVMs[0].invoke(() -> getLocalDataSet(partitionedRegionName));
+    final List<String> member2RealData =
+        this.memberVMs[1].invoke(() -> getLocalDataSet(partitionedRegionName));
+    final List<String> member3RealData =
+        this.memberVMs[2].invoke(() -> getLocalDataSet(partitionedRegionName));
 
-          Cache cache = getCache();
-          PartitionAttributesFactory paf = new PartitionAttributesFactory();
+    this.managerVM.invoke(this.testName.getMethodName(), () -> {
+      DistributedSystemMXBean distributedSystemMXBean =
+          this.managementTestRule.getSystemManagementService().getDistributedSystemMXBean();
+      DistributedRegionMXBean distributedRegionMXBean =
+          awaitDistributedRegionMXBean("/" + partitionedRegionName, 3);
 
-          paf.setRedundantCopies(2).setTotalNumBuckets(12);
+      String alias = "Waiting for all entries to get reflected at managing node";
+      int expectedEntryCount = values1.length + values2.length;
+      await(alias).until(() -> assertThat(distributedRegionMXBean.getSystemRegionEntryCount())
+          .isEqualTo(expectedEntryCount));
 
-          List<FixedPartitionAttributes> fpaList = createFixedPartitionList(2);
-          for (FixedPartitionAttributes fpa : fpaList) {
-            paf.addFixedPartitionAttributes(fpa);
-          }
-          paf.setPartitionResolver(new SingleHopQuarterPartitionResolver());
+      String query = "Select * from /" + partitionedRegionName;
 
-          RegionFactory rf = cache.createRegionFactory(RegionShortcut.PARTITION)
-              .setPartitionAttributes(paf.create());
+      String member1Result = distributedSystemMXBean.queryData(query, member1.getId(), 0);
+      verifyJsonIsValid(member1Result);
 
-          Region r = rf.create(PartitionedRegionName6);
+      String member2Result = distributedSystemMXBean.queryData(query, member2.getId(), 0);
+      verifyJsonIsValid(member2Result);
 
-          for (int i = 0; i < valArray2.length; i++) {
-            r.put(new Date(2013, 5, i + 5), valArray2[i]);
-          }
+      String member3Result = distributedSystemMXBean.queryData(query, member3.getId(), 0);
+      verifyJsonIsValid(member3Result);
 
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
+      for (String val : member1RealData) {
+        assertThat(member1Result).contains(val);
+      }
 
+      for (String val : member2RealData) {
+        assertThat(member2Result).contains(val);
       }
+
+      assertThat(member3Result).contains("No Data Found");
     });
+  }
 
-    this.managedNode3.invoke(new SerializableRunnable("testRegionsLocalDataSet: Create Region") {
-      public void run() {
-        try {
+  private Date getDate(final int year, final int month, final int date) {
+    Calendar calendar = Calendar.getInstance();
+    calendar.set(year, month, date);
+    return calendar.getTime();
+  }
 
-          Cache cache = getCache();
-          PartitionAttributesFactory paf = new PartitionAttributesFactory();
+  private void verifyJsonIsValid(final String jsonString) throws JSONException {
+    assertThat(jsonString, isJson());
+    assertThat(jsonString, hasJsonPath("$.result"));
+    assertThat(new JSONObject(jsonString)).isNotNull();
+  }
 
-          paf.setRedundantCopies(2).setTotalNumBuckets(12);
+  private void putDataInRegion(final String regionName, final Object[] portfolio, final int from,
+      final int to) {
+    Region region = this.managementTestRule.getCache().getRegion(regionName);
+    for (int i = from; i < to; i++) {
+      region.put(new Integer(i), portfolio[i]);
+    }
+  }
 
-          List<FixedPartitionAttributes> fpaList = createFixedPartitionList(3);
-          for (FixedPartitionAttributes fpa : fpaList) {
-            paf.addFixedPartitionAttributes(fpa);
-          }
-          paf.setPartitionResolver(new SingleHopQuarterPartitionResolver());
+  private void generateValuesInRegions() {
+    int COUNT_DESTINATION = 30;
+    int COUNT_FROM = 0;
 
-          RegionFactory rf = cache.createRegionFactory(RegionShortcut.PARTITION)
-              .setPartitionAttributes(paf.create());
+    // Create common Portfolios and NewPortfolios
+    final Portfolio[] portfolio = createPortfoliosAndPositions(COUNT_DESTINATION);
 
-          Region r = rf.create(PartitionedRegionName6);
+    // Fill local region
+    this.memberVMs[0]
+        .invoke(() -> putDataInRegion(LOCAL_REGION_NAME, portfolio, COUNT_FROM, COUNT_DESTINATION));
 
+    // Fill replicated region
+    this.memberVMs[0].invoke(
+        () -> putDataInRegion(REPLICATE_REGION_NAME1, portfolio, COUNT_FROM, COUNT_DESTINATION));
+    this.memberVMs[1].invoke(
+        () -> putDataInRegion(REPLICATE_REGION_NAME2, portfolio, COUNT_FROM, COUNT_DESTINATION));
 
+    // Fill Partition Region
+    this.memberVMs[0].invoke(
+        () -> putDataInRegion(PARTITIONED_REGION_NAME1, portfolio, COUNT_FROM, COUNT_DESTINATION));
+    this.memberVMs[0].invoke(
+        () -> putDataInRegion(PARTITIONED_REGION_NAME2, portfolio, COUNT_FROM, COUNT_DESTINATION));
+    this.memberVMs[0].invoke(
+        () -> putDataInRegion(PARTITIONED_REGION_NAME3, portfolio, COUNT_FROM, COUNT_DESTINATION));
+    this.memberVMs[0].invoke(
+        () -> putDataInRegion(PARTITIONED_REGION_NAME4, portfolio, COUNT_FROM, COUNT_DESTINATION));
+    this.memberVMs[0].invoke(
+        () -> putDataInRegion(PARTITIONED_REGION_NAME5, portfolio, COUNT_FROM, COUNT_DESTINATION));
+
+    this.memberVMs[0].invoke(() -> putPdxInstances(REPLICATE_REGION_NAME3));
+  }
 
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
+  private void putPdxInstances(final String regionName) throws CacheException {
+    Region region = this.managementTestRule.getCache().getRegion(regionName);
+
+    PdxInstanceFactory pdxInstanceFactory = PdxInstanceFactoryImpl.newCreator("Portfolio", false);
+    pdxInstanceFactory.writeInt("ID", 111);
+    pdxInstanceFactory.writeString("status", "active");
+    pdxInstanceFactory.writeString("secId", "IBM");
+    PdxInstance pdxInstance = pdxInstanceFactory.create();
+    region.put("IBM", pdxInstance);
+
+    pdxInstanceFactory = PdxInstanceFactoryImpl.newCreator("Portfolio", false);
+    pdxInstanceFactory.writeInt("ID", 222);
+    pdxInstanceFactory.writeString("status", "inactive");
+    pdxInstanceFactory.writeString("secId", "YHOO");
+    pdxInstance = pdxInstanceFactory.create();
+    region.put("YHOO", pdxInstance);
+
+    pdxInstanceFactory = PdxInstanceFactoryImpl.newCreator("Portfolio", false);
+    pdxInstanceFactory.writeInt("ID", 333);
+    pdxInstanceFactory.writeString("status", "active");
+    pdxInstanceFactory.writeString("secId", "GOOGL");
+    pdxInstance = pdxInstanceFactory.create();
+    region.put("GOOGL", pdxInstance);
+
+    pdxInstanceFactory = PdxInstanceFactoryImpl.newCreator("Portfolio", false);
+    pdxInstanceFactory.writeInt("ID", 111);
+    pdxInstanceFactory.writeString("status", "inactive");
+    pdxInstanceFactory.writeString("secId", "VMW");
+    pdxInstance = pdxInstanceFactory.create();
+    region.put("VMW", pdxInstance);
+  }
+
+  private void putBigInstances(final String regionName) {
+    Region region = this.managementTestRule.getCache().getRegion(regionName);
 
+    for (int i = 0; i < 1200; i++) {
+      List<String> bigCollection = new ArrayList<>();
+      for (int j = 0; j < 200; j++) {
+        bigCollection.add(BIG_COLLECTION_ELEMENT_ + j);
       }
-    });
+      region.put(BIG_COLLECTION_ + i, bigCollection);
+    }
+  }
 
-    final List<String> member1RealData = (List<String>) managedNode1
-        .invoke(() -> QueryDataDUnitTest.getLocalDataSet(PartitionedRegionName6));
+  private void createLocalRegion() {
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.LOCAL)
+        .create(LOCAL_REGION_NAME);
+  }
 
-    final List<String> member2RealData = (List<String>) managedNode2
-        .invoke(() -> QueryDataDUnitTest.getLocalDataSet(PartitionedRegionName6));
+  private void createReplicatedRegion() {
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.REPLICATE)
+        .create(REPLICATE_REGION_NAME1);
+  }
 
-    final List<String> member3RealData = (List<String>) managedNode3
-        .invoke(() -> QueryDataDUnitTest.getLocalDataSet(PartitionedRegionName6));
+  private void createColocatedPR() {
+    PartitionResolver testKeyBasedResolver = new TestPartitionResolver();
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION)
+        .setPartitionAttributes(new PartitionAttributesFactory().setTotalNumBuckets(NUM_OF_BUCKETS)
+            .setPartitionResolver(testKeyBasedResolver).create())
+        .create(PARTITIONED_REGION_NAME1);
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION)
+        .setPartitionAttributes(new PartitionAttributesFactory().setTotalNumBuckets(NUM_OF_BUCKETS)
+            .setPartitionResolver(testKeyBasedResolver).setColocatedWith(PARTITIONED_REGION_NAME1)
+            .create())
+        .create(PARTITIONED_REGION_NAME2);
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION)
+        .setPartitionAttributes(new PartitionAttributesFactory().setTotalNumBuckets(NUM_OF_BUCKETS)
+            .setPartitionResolver(testKeyBasedResolver).setColocatedWith(PARTITIONED_REGION_NAME2)
+            .create())
+        .create(PARTITIONED_REGION_NAME3);
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION)
+        .setPartitionAttributes(new PartitionAttributesFactory().setTotalNumBuckets(NUM_OF_BUCKETS)
+            .setPartitionResolver(testKeyBasedResolver).create())
+        .create(PARTITIONED_REGION_NAME4); // not collocated
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.PARTITION)
+        .setPartitionAttributes(new PartitionAttributesFactory().setTotalNumBuckets(NUM_OF_BUCKETS)
+            .setPartitionResolver(testKeyBasedResolver).setColocatedWith(PARTITIONED_REGION_NAME4)
+            .create())
+        .create(PARTITIONED_REGION_NAME5); // collocated with 4
+  }
 
+  private void createDistributedRegion(final String regionName) {
+    this.managementTestRule.getCache().createRegionFactory(RegionShortcut.REPLICATE)
+        .create(regionName);
+  }
 
+  private void createRegionsInNodes()
+      throws InterruptedException, TimeoutException, ExecutionException {
+    // Create local Region on servers
+    this.memberVMs[0].invoke(() -> createLocalRegion());
 
-    this.managingNode.invoke(new SerializableRunnable("testRegionsLocalDataSet") {
-      public void run() {
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        assertNotNull(bean);
+    // Create ReplicatedRegion on servers
+    this.memberVMs[0].invoke(() -> createReplicatedRegion());
+    this.memberVMs[1].invoke(() -> createReplicatedRegion());
+    this.memberVMs[2].invoke(() -> createReplicatedRegion());
+
+    this.memberVMs[1].invoke(() -> createDistributedRegion(REPLICATE_REGION_NAME2));
+    this.memberVMs[0].invoke(() -> createDistributedRegion(REPLICATE_REGION_NAME3));
+    this.memberVMs[0].invoke(() -> createDistributedRegion(REPLICATE_REGION_NAME4));
+
+    // Create two co-located PartitionedRegions On Servers.
+    this.memberVMs[0].invoke(() -> createColocatedPR());
+    this.memberVMs[1].invoke(() -> createColocatedPR());
+    this.memberVMs[2].invoke(() -> createColocatedPR());
+
+    this.managerVM.invoke("Wait for all Region Proxies to get replicated", () -> {
+      awaitDistributedRegionMXBean("/" + PARTITIONED_REGION_NAME1, 3);
+      awaitDistributedRegionMXBean("/" + PARTITIONED_REGION_NAME2, 3);
+      awaitDistributedRegionMXBean("/" + PARTITIONED_REGION_NAME3, 3);
+      awaitDistributedRegionMXBean("/" + PARTITIONED_REGION_NAME4, 3);
+      awaitDistributedRegionMXBean("/" + PARTITIONED_REGION_NAME5, 3);
+      awaitDistributedRegionMXBean("/" + REPLICATE_REGION_NAME1, 3);
+      awaitDistributedRegionMXBean("/" + REPLICATE_REGION_NAME2, 1);
+      awaitDistributedRegionMXBean("/" + REPLICATE_REGION_NAME3, 1);
+      awaitDistributedRegionMXBean("/" + REPLICATE_REGION_NAME4, 1);
+    });
+  }
 
-        try {
-          String query = "Select * from /" + PartitionedRegionName6;
+  private List<String> getLocalDataSet(final String region) {
+    PartitionedRegion partitionedRegion =
+        PartitionedRegionHelper.getPartitionedRegion(region, this.managementTestRule.getCache());
+    Set<BucketRegion> localPrimaryBucketRegions =
+        partitionedRegion.getDataStore().getAllLocalPrimaryBucketRegions();
 
-          try {
-            final DistributedRegionMXBean regionMBean =
-                MBeanUtil.getDistributedRegionMbean("/" + PartitionedRegionName6, 3);
+    List<String> allPrimaryValues = new ArrayList<>();
 
-            Wait.waitForCriterion(new WaitCriterion() {
+    for (BucketRegion bucketRegion : localPrimaryBucketRegions) {
+      for (Object value : bucketRegion.values()) {
+        allPrimaryValues.add((String) value);
+      }
+    }
 
-              public String description() {
-                return "Waiting for all entries to get reflected at managing node";
-              }
+    return allPrimaryValues;
+  }
 
-              public boolean done() {
+  private List<FixedPartitionAttributes> createFixedPartitionList(final int primaryIndex) {
+    List<FixedPartitionAttributes> fixedPartitionAttributesList = new ArrayList<>();
+    if (primaryIndex == 1) {
+      fixedPartitionAttributesList.add(createFixedPartition("Q1", true, 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q2", 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q3", 3));
+    }
+    if (primaryIndex == 2) {
+      fixedPartitionAttributesList.add(createFixedPartition("Q1", 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q2", true, 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q3", 3));
+    }
+    if (primaryIndex == 3) {
+      fixedPartitionAttributesList.add(createFixedPartition("Q1", 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q2", 3));
+      fixedPartitionAttributesList.add(createFixedPartition("Q3", true, 3));
+    }
+    return fixedPartitionAttributesList;
+  }
 
-                boolean done = (regionMBean
-                    .getSystemRegionEntryCount() == (valArray1.length + valArray2.length));
-                return done;
-              }
+  private MemberMXBean awaitMemberMXBeanProxy(final DistributedMember member) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    ObjectName objectName = service.getMemberMBeanName(member);
+    String alias = "awaiting MemberMXBean proxy for " + member;
 
-            }, MAX_WAIT, 1000, true);
+    await(alias)
+        .until(() -> assertThat(service.getMBeanProxy(objectName, MemberMXBean.class)).isNotNull());
 
-            LogWriterUtils.getLogWriter().info("member1RealData  is = " + member1RealData);
-            LogWriterUtils.getLogWriter().info("member2RealData  is = " + member2RealData);
-            LogWriterUtils.getLogWriter().info("member3RealData  is = " + member3RealData);
+    return service.getMBeanProxy(objectName, MemberMXBean.class);
+  }
 
-            String member1Result = bean.queryData(query, member1.getId(), 0);
-            LogWriterUtils.getLogWriter().info("member1Result " + query + " is = " + member1Result);
+  private DistributedSystemMXBean awaitDistributedSystemMXBean() {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
+    await().until(() -> assertThat(service.getDistributedSystemMXBean()).isNotNull());
 
-            String member2Result = bean.queryData(query, member2.getId(), 0);
-            LogWriterUtils.getLogWriter().info("member2Result " + query + " is = " + member2Result);
+    return service.getDistributedSystemMXBean();
+  }
 
-            String member3Result = bean.queryData(query, member3.getId(), 0);
-            LogWriterUtils.getLogWriter().info("member3Result " + query + " is = " + member3Result);
+  private DistributedRegionMXBean awaitDistributedRegionMXBean(final String name) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
-            for (String val : member1RealData) {
-              assertTrue(member1Result.contains(val));
-            }
+    await().until(() -> assertThat(service.getDistributedRegionMXBean(name)).isNotNull());
 
-            for (String val : member2RealData) {
-              assertTrue(member2Result.contains(val));
-            }
+    return service.getDistributedRegionMXBean(name);
+  }
 
-            assertTrue(member3Result.contains("No Data Found"));
-          } catch (Exception e) {
-            fail(e.getMessage());
-          }
+  private DistributedRegionMXBean awaitDistributedRegionMXBean(final String name,
+      final int memberCount) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
 
-        } catch (Exception e) {
-          fail(e.getMessage());
-        }
+    await().until(() -> assertThat(service.getDistributedRegionMXBean(name)).isNotNull());
+    await().until(() -> assertThat(service.getDistributedRegionMXBean(name).getMemberCount())
+        .isEqualTo(memberCount));
 
-      }
-    });
+    return service.getDistributedRegionMXBean(name);
   }
 
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(2, MINUTES);
+  }
 
-  private static List<String> getLocalDataSet(String region) {
-    PartitionedRegion parRegion =
-        PartitionedRegionHelper.getPartitionedRegion(region, GemFireCacheImpl.getExisting());
-    Set<BucketRegion> localPrimaryBucketRegions =
-        parRegion.getDataStore().getAllLocalPrimaryBucketRegions();
-    List<String> allPrimaryVals = new ArrayList<String>();
-    for (BucketRegion brRegion : localPrimaryBucketRegions) {
-      for (Object obj : brRegion.values()) {
-        allPrimaryVals.add((String) obj);
-      }
+  private ConditionFactory await(final String alias) {
+    return Awaitility.await(alias).atMost(2, MINUTES);
+  }
 
-    }
+  private static class TestPartitionResolver implements PartitionResolver {
 
-    return allPrimaryVals;
-  }
+    @Override
+    public void close() {}
 
-  /**
-   * creates a Fixed Partition List to be used for Fixed Partition Region
-   * 
-   * @param primaryIndex index for each fixed partition
-   */
-  private static List<FixedPartitionAttributes> createFixedPartitionList(int primaryIndex) {
-    List<FixedPartitionAttributes> fpaList = new ArrayList<FixedPartitionAttributes>();
-    if (primaryIndex == 1) {
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q1", true, 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q2", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q3", 3));
+    @Override
+    public Serializable getRoutingObject(EntryOperation opDetails) {
+      return (((Integer) opDetails.getKey()).intValue() % NUM_OF_BUCKETS);
     }
-    if (primaryIndex == 2) {
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q1", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q2", true, 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q3", 3));
-    }
-    if (primaryIndex == 3) {
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q1", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q2", 3));
-      fpaList.add(FixedPartitionAttributes.createFixedPartition("Q3", true, 3));
+
+    @Override
+    public String getName() {
+      return getClass().getName();
     }
-    return fpaList;
   }
 }


[5/8] geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/ManagementTestBase.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/ManagementTestBase.java b/geode-core/src/test/java/org/apache/geode/management/ManagementTestBase.java
index 85d42ee..ef1c4fa 100644
--- a/geode-core/src/test/java/org/apache/geode/management/ManagementTestBase.java
+++ b/geode-core/src/test/java/org/apache/geode/management/ManagementTestBase.java
@@ -17,15 +17,17 @@ package org.apache.geode.management;
 import static org.apache.geode.distributed.ConfigurationProperties.*;
 import static org.junit.Assert.*;
 
+import java.lang.management.ManagementFactory;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Properties;
 import java.util.Set;
-import javax.management.MBeanServer;
+
 import javax.management.ObjectName;
 
-import org.apache.geode.LogWriter;
+import org.junit.Rule;
+
 import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.CacheFactory;
 import org.apache.geode.cache.Region;
@@ -35,39 +37,32 @@ import org.apache.geode.distributed.DistributedMember;
 import org.apache.geode.distributed.DistributedSystem;
 import org.apache.geode.distributed.internal.InternalDistributedSystem;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.statistics.SampleCollector;
 import org.apache.geode.management.internal.FederatingManager;
 import org.apache.geode.management.internal.LocalManager;
-import org.apache.geode.management.internal.MBeanJMXAdapter;
 import org.apache.geode.management.internal.ManagementStrings;
 import org.apache.geode.management.internal.SystemManagementService;
 import org.apache.geode.test.dunit.Assert;
 import org.apache.geode.test.dunit.AsyncInvocation;
 import org.apache.geode.test.dunit.Host;
 import org.apache.geode.test.dunit.Invoke;
+import org.apache.geode.test.dunit.LogWriterUtils;
 import org.apache.geode.test.dunit.SerializableCallable;
 import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
 import org.apache.geode.test.dunit.Wait;
 import org.apache.geode.test.dunit.WaitCriterion;
+import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
 import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
+import org.apache.geode.test.dunit.rules.DistributedRestoreSystemProperties;
 
 @SuppressWarnings("serial")
-public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
+public abstract class ManagementTestBase extends JUnit4CacheTestCase {
 
   private static final int MAX_WAIT = 70 * 1000;
 
-  /**
-   * log writer instance
-   */
-  private static LogWriter logWriter;
-
-  private static Properties props = new Properties();
-
-  /**
-   * Distributed System
-   */
-  protected static DistributedSystem ds;
+  // protected static DistributedSystem ds;
+  protected static ManagementService managementService;
+  // protected static Cache cache;
 
   /**
    * List containing all the Managed Node VM
@@ -79,23 +74,14 @@ public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
    */
   protected static VM managingNode;
 
-  /**
-   * Management Service
-   */
-  protected static ManagementService managementService;
-
   protected static VM managedNode1;
   protected static VM managedNode2;
   protected static VM managedNode3;
   protected static VM locatorVM;
 
-  private static SampleCollector sampleCollector;
-
-  protected static MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
-
-  private static int mcastPort;
-
-  protected static Cache cache;
+  @Rule
+  public DistributedRestoreSystemProperties restoreSystemProperties =
+      new DistributedRestoreSystemProperties();
 
   @Override
   public final void postSetUp() throws Exception {
@@ -119,16 +105,14 @@ public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
   protected void postSetUpManagementTestBase() throws Exception {}
 
   @Override
-  public final void preTearDown() throws Exception {
+  public final void preTearDownCacheTestCase() throws Exception {
     preTearDownManagementTestBase();
 
-    closeAllCache();
-    managementService = null;
-
-    mcastPort = 0;
-    disconnectAllFromDS();
-    props.clear();
+  }
 
+  @Override
+  public final void postTearDownCacheTestCase() throws Exception {
+    managementService = null;
     postTearDownManagementTestBase();
   }
 
@@ -136,99 +120,49 @@ public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
 
   protected void postTearDownManagementTestBase() throws Exception {}
 
-  public void closeAllCache() throws Exception {
-    closeCache(managingNode);
-    closeCache(managedNode1);
-    closeCache(managedNode2);
-    closeCache(managedNode3);
-    cache = null;
-  }
-
-  /**
-   * Enable system property gemfire.disableManagement false in each VM.
-   */
-  public void enableManagement() {
-    Invoke.invokeInEveryVM(new SerializableRunnable("Enable Management") {
-      public void run() {
-        System.setProperty(InternalDistributedSystem.DISABLE_MANAGEMENT_PROPERTY, "false");
-      }
-    });
-
-  }
-
-  /**
-   * Disable system property gemfire.disableManagement true in each VM.
-   */
-  public void disableManagement() {
-    Invoke.invokeInEveryVM(new SerializableRunnable("Disable Management") {
-      public void run() {
-        System.setProperty(InternalDistributedSystem.DISABLE_MANAGEMENT_PROPERTY, "true");
-      }
-    });
-
-  }
-
   /**
    * managingNodeFirst variable tests for two different test cases where Managing & Managed Node
    * creation time lines are reversed.
    */
-  public void initManagement(boolean managingNodeFirst) throws Exception {
-
+  protected void initManagement(final boolean managingNodeFirst) throws Exception {
     if (managingNodeFirst) {
       createManagementCache(managingNode);
       startManagingNode(managingNode);
-
       for (VM vm : managedNodeList) {
         createCache(vm);
-
       }
 
     } else {
       for (VM vm : managedNodeList) {
         createCache(vm);
-
       }
       createManagementCache(managingNode);
       startManagingNode(managingNode);
     }
   }
 
-  public void createCache(VM vm1) throws Exception {
-    vm1.invoke(new SerializableRunnable("Create Cache") {
-      public void run() {
-        createCache(false);
-      }
+  protected void createCache(final VM vm1) throws Exception {
+    vm1.invoke("Create Cache", () -> {
+      createCache(false);
     });
-
   }
 
-  public void createCache(VM vm1, final Properties props) throws Exception {
-    vm1.invoke(new SerializableRunnable("Create Cache") {
-      public void run() {
-        createCache(props);
-      }
+  protected void createCache(final VM vm1, final Properties props) throws Exception {
+    vm1.invoke("Create Cache", () -> {
+      createCache(props);
     });
-
   }
 
-  public Cache createCache(Properties props) {
-    System.setProperty("dunitLogPerTest", "true");
-    props.setProperty(LOG_FILE, getTestMethodName() + "-.log");
-    ds = getSystem(props);
-    cache = CacheFactory.create(ds);
+  private Cache createCache(final Properties props) {
+    Cache cache = getCache(props);
     managementService = ManagementService.getManagementService(cache);
-    logWriter = ds.getLogWriter();
-    assertNotNull(cache);
-    assertNotNull(managementService);
-    return cache;
-  }
 
-  public Cache getCache() {
     return cache;
   }
 
-  public Cache createCache(boolean management) {
-    System.setProperty("dunitLogPerTest", "true");
+  protected Cache createCache(final boolean management) {
+
+    Properties props = new Properties();
     if (management) {
       props.setProperty(JMX_MANAGER, "true");
       props.setProperty(JMX_MANAGER_START, "false");
@@ -238,68 +172,48 @@ public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
     props.setProperty(ENABLE_TIME_STATISTICS, "true");
     props.setProperty(STATISTIC_SAMPLING_ENABLED, "true");
     props.setProperty(LOG_FILE, getTestMethodName() + "-.log");
-    ds = getSystem(props);
-    cache = CacheFactory.create(ds);
+
+    Cache cache = getCache(props);
     managementService = ManagementService.getManagementService(cache);
-    logWriter = ds.getLogWriter();
-    assertNotNull(cache);
-    assertNotNull(managementService);
+
     return cache;
   }
 
-  public void createManagementCache(VM vm1) throws Exception {
-    vm1.invoke(new SerializableRunnable("Create Management Cache") {
-      public void run() {
-        createCache(true);
-      }
+  protected void createManagementCache(final VM vm1) throws Exception {
+    vm1.invoke("Create Management Cache", () -> {
+      createCache(true);
     });
   }
 
-  public void closeCache(VM vm1) throws Exception {
-    vm1.invoke(new SerializableRunnable("Close Cache") {
-      public void run() {
-        GemFireCacheImpl existingInstance = GemFireCacheImpl.getInstance();
-        if (existingInstance != null) {
-          existingInstance.close();
-        }
-        InternalDistributedSystem ds = InternalDistributedSystem.getConnectedInstance();
-        if (ds != null) {
-          ds.disconnect();
-        }
+  protected void closeCache(final VM vm1) throws Exception {
+    vm1.invoke("Close Cache", () -> {
+      GemFireCacheImpl existingInstance = GemFireCacheImpl.getInstance();
+      if (existingInstance != null) {
+        existingInstance.close();
+      }
+      InternalDistributedSystem ds = InternalDistributedSystem.getConnectedInstance();
+      if (ds != null) {
+        ds.disconnect();
       }
     });
-
-  }
-
-  public void closeCache() throws Exception {
-    GemFireCacheImpl existingInstance = GemFireCacheImpl.getInstance();
-    if (existingInstance != null) {
-      existingInstance.close();
-    }
-    InternalDistributedSystem ds = InternalDistributedSystem.getConnectedInstance();
-    if (ds != null) {
-      ds.disconnect();
-    }
   }
 
-  public String getMemberId(final VM vm) {
-    SerializableCallable getMember = new SerializableCallable("getMemberId") {
-      public Object call() throws Exception {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        return cache.getDistributedSystem().getDistributedMember().getId();
-      }
-    };
-    return (String) vm.invoke(getMember);
+  protected String getMemberId(final VM vm) {
+    return vm.invoke("getMemberId", () -> {
+      GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+      return cache.getDistributedSystem().getDistributedMember().getId();
+    });
   }
 
   protected static void waitForProxy(final ObjectName objectName, final Class interfaceClass) {
-
     Wait.waitForCriterion(new WaitCriterion() {
+      @Override
       public String description() {
         return "Waiting for the proxy of " + objectName.getCanonicalName()
             + " to get propagated to Manager";
       }
 
+      @Override
       public boolean done() {
         SystemManagementService service = (SystemManagementService) managementService;
         if (service.getMBeanProxy(objectName, interfaceClass) != null) {
@@ -308,205 +222,55 @@ public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
           return false;
         }
       }
-
     }, MAX_WAIT, 500, true);
   }
 
-  protected void runManagementTaskAdhoc() {
-    SystemManagementService service = (SystemManagementService) managementService;
-    service.getLocalManager().runManagementTaskAdhoc();
-  }
-
   /**
    * Marks a VM as Managing
-   *
-   * @throws Exception
    */
-  public void startManagingNode(VM vm1) throws Exception {
-    vm1.invoke(new SerializableRunnable("Start Being Managing Node") {
-      public void run() {
-        startBeingManagingNode();
-      }
-    });
-
-  }
-
-  public void startBeingManagingNode() {
-    Cache existingCache = GemFireCacheImpl.getInstance();
-    if (existingCache != null && !existingCache.isClosed()) {
+  protected void startManagingNode(final VM vm1) {
+    vm1.invoke("Start Being Managing Node", () -> {
+      Cache existingCache = GemFireCacheImpl.getInstance();
+      // if (existingCache != null && !existingCache.isClosed()) {
       managementService = ManagementService.getManagementService(existingCache);
       SystemManagementService service = (SystemManagementService) managementService;
       service.createManager();
       service.startManager();
-    }
-  }
-
-  /**
-   * Marks a VM as Managing
-   *
-   * @throws Exception
-   */
-  public void startManagingNodeAsync(VM vm1) throws Exception {
-    vm1.invokeAsync(new SerializableRunnable("Start Being Managing Node") {
-
-      public void run() {
-        Cache existingCache = GemFireCacheImpl.getInstance();
-        if (existingCache != null && !existingCache.isClosed()) {
-          managementService = ManagementService.getManagementService(existingCache);
-          managementService.startManager();
-        }
-
-      }
+      // }
     });
-
   }
 
   /**
    * Stops a VM as a Managing node
-   *
-   * @throws Exception
-   */
-  public void stopManagingNode(VM vm1) throws Exception {
-    vm1.invoke(new SerializableRunnable("Stop Being Managing Node") {
-      public void run() {
-        Cache existingCache = GemFireCacheImpl.getInstance();
-        if (existingCache != null && !existingCache.isClosed()) {
-          if (managementService.isManager()) {
-            managementService.stopManager();
-          }
-
-        }
-
-      }
-    });
-
-  }
-
-  /**
-   * Check various resources clean up Once a VM stops being managable it should remove all the
-   * artifacts of management namely a) Notification region b) Monitoring Region c) Management task
-   * should stop
-   */
-  public void checkManagedNodeCleanup(VM vm) throws Exception {
-    vm.invoke(new SerializableRunnable("Managing Node Clean up") {
-
-      public void run() {
-        Cache existingCache = GemFireCacheImpl.getInstance();
-        if (existingCache != null) {
-          // Cache is closed
-          assertEquals(true, existingCache.isClosed());
-          // ManagementService should throw exception
-          LocalManager localManager =
-              ((SystemManagementService) managementService).getLocalManager();
-          // Check Monitoring region destroyed
-          Region monitoringRegion =
-              localManager.getManagementResourceRepo().getLocalMonitoringRegion();
-          assertEquals(null, monitoringRegion);
-          // check Notification region is destroyed
-          Region notifRegion =
-              localManager.getManagementResourceRepo().getLocalNotificationRegion();
-          assertEquals(null, notifRegion);
-          // check ManagementTask is stopped
-          assertEquals(true, localManager.getFederationSheduler().isShutdown());
-
-        }
-
-      }
-    });
-
-  }
-
-  /**
-   * Check various resources clean up Once a VM stops being Managing.It should remove all the
-   * artifacts of management namely a) proxies b) Monitoring Region c) Management task should stop
    */
-
-  public void checkProxyCleanup(VM vm) throws Exception {
-
-    vm.invoke(new SerializableRunnable("Managing Node Clean up") {
-
-      public void run() {
-
-        try {
-          GemFireCacheImpl existingCache = GemFireCacheImpl.getInstance();
-          if (existingCache == null) {
-            return;
-          }
-
-          assertEquals(false, existingCache.isClosed());
-          // ManagementService should not be closed
-
-          Set<DistributedMember> otherMemberSet =
-              existingCache.getDistributionManager().getOtherDistributionManagerIds();
-
-          Iterator<DistributedMember> it = otherMemberSet.iterator();
-          FederatingManager federatingManager =
-              ((SystemManagementService) managementService).getFederatingManager();
-
-          // check Proxy factory. There should not be any proxies left
-          DistributedMember member;
-          while (it.hasNext()) {
-            member = it.next();
-
-            assertNull(federatingManager.getProxyFactory().findAllProxies(member));
-          }
-
-        } catch (ManagementException e) {
-          Assert.fail("failed with ManagementException", e);
+  protected void stopManagingNode(final VM vm1) {
+    vm1.invoke("Stop Being Managing Node", () -> {
+      Cache existingCache = GemFireCacheImpl.getInstance();
+      if (existingCache != null && !existingCache.isClosed()) {
+        if (managementService.isManager()) {
+          managementService.stopManager();
         }
       }
     });
-
-  }
-
-  /**
-   * All the expected exceptions are checked here
-   *
-   * @param e
-   * @return is failed
-   */
-  public boolean checkManagementExceptions(ManagementException e) {
-
-    if (e.getMessage().equals(ManagementStrings.Management_Service_CLOSED_CACHE)
-        || e.getMessage().equals(
-            ManagementStrings.Management_Service_MANAGEMENT_SERVICE_IS_CLOSED.toLocalizedString())
-        || e.getMessage()
-            .equals(ManagementStrings.Management_Service_MANAGEMENT_SERVICE_NOT_STARTED_YET
-                .toLocalizedString())
-        || e.getMessage().equals(
-            ManagementStrings.Management_Service_NOT_A_GEMFIRE_DOMAIN_MBEAN.toLocalizedString())
-        || e.getMessage().equals(
-            ManagementStrings.Management_Service_NOT_A_MANAGING_NODE_YET.toLocalizedString())
-        || e.getMessage()
-            .equals(ManagementStrings.Management_Service_OPERATION_NOT_ALLOWED_FOR_CLIENT_CACHE
-                .toLocalizedString())
-        || e.getMessage()
-            .equals(ManagementStrings.Management_Service_PROXY_NOT_AVAILABLE.toLocalizedString())) {
-
-      return false;
-    }
-    return true;
   }
 
-  public static List<VM> getManagedNodeList() {
+  protected static List<VM> getManagedNodeList() {
     return managedNodeList;
   }
 
-  public static VM getManagingNode() {
+  protected static VM getManagingNode() {
     return managingNode;
   }
 
-  public static ManagementService getManagementService() {
+  protected static ManagementService getManagementService() {
     return managementService;
   }
 
   /**
    * Creates a Distributed region
-   *
-   * @param vm reference to VM
-   * @param regionName name of the distributed region
    */
-  protected void createDistributedRegion(VM vm, final String regionName) throws Exception {
+  protected void createDistributedRegion(final VM vm, final String regionName)
+      throws InterruptedException {
     AsyncInvocation future = createDistributedRegionAsync(vm, regionName);
     future.join(MAX_WAIT);
     if (future.isAlive()) {
@@ -519,169 +283,103 @@ public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
 
   /**
    * Creates a Local region
-   *
-   * @param vm reference to VM
-   * @param localRegionName name of the local region
    */
-  protected void createLocalRegion(VM vm, final String localRegionName) throws Exception {
-    SerializableRunnable createLocalRegion = new SerializableRunnable("Create Local region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        RegionFactory rf = cache.createRegionFactory(RegionShortcut.LOCAL);
-
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Creating Local Region");
-        rf.create(localRegionName);
-
-      }
-    };
-    vm.invoke(createLocalRegion);
+  protected void createLocalRegion(final VM vm, final String localRegionName) throws Exception {
+    vm.invoke("Create Local region", () -> {
+      GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+      SystemManagementService service = (SystemManagementService) getManagementService();
+      RegionFactory rf = cache.createRegionFactory(RegionShortcut.LOCAL);
+
+      LogWriterUtils.getLogWriter().info("Creating Local Region");
+      rf.create(localRegionName);
+    });
   }
 
   /**
    * Creates a Sub region
-   *
-   * @param vm reference to VM
    */
-  protected void createSubRegion(VM vm, final String parentRegionPath, final String subregionName)
-      throws Exception {
-    SerializableRunnable createSubRegion = new SerializableRunnable("Create Sub region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        Region region = cache.getRegion(parentRegionPath);
-
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Creating Sub Region");
-        region.createSubregion(subregionName, region.getAttributes());
-
-      }
-    };
-    vm.invoke(createSubRegion);
-  }
-
-  /**
-   * Puts in distributed region
-   *
-   * @param vm
-   */
-  protected void putInDistributedRegion(final VM vm, final String key, final String value,
-      final String regionPath) {
-    SerializableRunnable put = new SerializableRunnable("Put In Distributed Region") {
-      public void run() {
-
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Region region = cache.getRegion(regionPath);
-        region.put(key, value);
-
-      }
-    };
-    vm.invoke(put);
+  protected void createSubRegion(final VM vm, final String parentRegionPath,
+      final String subregionName) throws Exception {
+    vm.invoke("Create Sub region", () -> {
+      GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+      SystemManagementService service = (SystemManagementService) getManagementService();
+      Region region = cache.getRegion(parentRegionPath);
+
+      LogWriterUtils.getLogWriter().info("Creating Sub Region");
+      region.createSubregion(subregionName, region.getAttributes());
+    });
   }
 
   /**
    * Creates a Distributed Region
-   *
-   * @param vm
    */
-  protected AsyncInvocation createDistributedRegionAsync(final VM vm, final String regionName) {
-    SerializableRunnable createRegion = new SerializableRunnable("Create Distributed region") {
-      public void run() {
-
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-
-        RegionFactory rf = cache.createRegionFactory(RegionShortcut.REPLICATE);
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Creating Dist Region");
-        rf.create(regionName);
-
-      }
-    };
-    return vm.invokeAsync(createRegion);
+  private AsyncInvocation createDistributedRegionAsync(final VM vm, final String regionName) {
+    return vm.invokeAsync("Create Distributed region", () -> {
+      GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+      SystemManagementService service = (SystemManagementService) getManagementService();
+
+      RegionFactory rf = cache.createRegionFactory(RegionShortcut.REPLICATE);
+      LogWriterUtils.getLogWriter().info("Creating Dist Region");
+      rf.create(regionName);
+    });
   }
 
   /**
    * Creates a partition Region
-   *
-   * @param vm
    */
   protected void createPartitionRegion(final VM vm, final String partitionRegionName) {
-    SerializableRunnable createParRegion = new SerializableRunnable("Create Partitioned region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        RegionFactory rf = cache.createRegionFactory(RegionShortcut.PARTITION_REDUNDANT);
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Creating Par Region");
-        rf.create(partitionRegionName);
-
-      }
-    };
-    vm.invoke(createParRegion);
-  }
-
-  /**
-   * closes a Distributed Region
-   *
-   * @param vm
-   */
-  protected void closeRegion(final VM vm, final String regionPath) {
-    SerializableRunnable closeRegion = new SerializableRunnable("Close Distributed region") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-
-        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().info("Closing Dist Region");
-        Region region = cache.getRegion(regionPath);
-        region.close();
-
-      }
-    };
-    vm.invoke(closeRegion);
+    vm.invoke("Create Partitioned region", () -> {
+      GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+      SystemManagementService service = (SystemManagementService) getManagementService();
+      RegionFactory rf = cache.createRegionFactory(RegionShortcut.PARTITION_REDUNDANT);
+      LogWriterUtils.getLogWriter().info("Creating Par Region");
+      rf.create(partitionRegionName);
+    });
   }
 
-  public void waitForAllMembers(final int expectedCount) {
+  protected void waitForAllMembers(final int expectedCount) {
     ManagementService service = getManagementService();
     final DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
 
     assertNotNull(service.getDistributedSystemMXBean());
 
     Wait.waitForCriterion(new WaitCriterion() {
+      @Override
       public String description() {
         return "Waiting All members to intimate DistributedSystemMBean";
       }
 
+      @Override
       public boolean done() {
         if (bean.listMemberObjectNames() != null) {
-
-          org.apache.geode.test.dunit.LogWriterUtils.getLogWriter()
+          LogWriterUtils.getLogWriter()
               .info("Member Length " + bean.listMemberObjectNames().length);
-
         }
-
         if (bean.listMemberObjectNames().length >= expectedCount) {
           return true;
         } else {
           return false;
         }
-
       }
-
     }, MAX_WAIT, 500, true);
 
     assertNotNull(bean.getManagerObjectName());
   }
 
-  public static void waitForRefresh(final int expectedRefreshCount, final ObjectName objectName) {
+  protected static void waitForRefresh(final int expectedRefreshCount,
+      final ObjectName objectName) {
     final ManagementService service = getManagementService();
 
-    final long currentTime = System.currentTimeMillis();
-
     Wait.waitForCriterion(new WaitCriterion() {
-      int actualRefreshCount = 0;
-      long lastRefreshTime = service.getLastUpdateTime(objectName);
+      private int actualRefreshCount = 0;
+      private long lastRefreshTime = service.getLastUpdateTime(objectName);
 
+      @Override
       public String description() {
         return "Waiting For Proxy Refresh Count = " + expectedRefreshCount;
       }
 
+      @Override
       public boolean done() {
         long newRefreshTime = service.getLastUpdateTime(objectName);
         if (newRefreshTime > lastRefreshTime) {
@@ -694,12 +392,10 @@ public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
         }
         return false;
       }
-
     }, MAX_WAIT, 500, true);
-
   }
 
-  public DistributedMember getMember(final VM vm) {
+  protected DistributedMember getMember(final VM vm) {
     SerializableCallable getMember = new SerializableCallable("Get Member") {
       public Object call() {
         GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
@@ -709,4 +405,14 @@ public abstract class ManagementTestBase extends JUnit4DistributedTestCase {
     };
     return (DistributedMember) vm.invoke(getMember);
   }
+
+  protected boolean mbeanExists(final ObjectName objectName) {
+    return ManagementFactory.getPlatformMBeanServer().isRegistered(objectName);
+  }
+
+  protected <T> T getMBeanProxy(final ObjectName objectName, Class<T> interfaceClass) {
+    SystemManagementService service =
+        (SystemManagementService) ManagementService.getManagementService(getCache());
+    return service.getMBeanProxy(objectName, interfaceClass);
+  }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/ManagementTestRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/ManagementTestRule.java b/geode-core/src/test/java/org/apache/geode/management/ManagementTestRule.java
new file mode 100644
index 0000000..e97a652
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/ManagementTestRule.java
@@ -0,0 +1,437 @@
+/*
+ * 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.geode.management;
+
+import static org.apache.geode.distributed.ConfigurationProperties.*;
+import static org.apache.geode.test.dunit.Host.*;
+import static org.assertj.core.api.Assertions.*;
+
+import java.io.Serializable;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.util.HashSet;
+import java.util.Properties;
+import java.util.Set;
+
+import org.junit.rules.MethodRule;
+import org.junit.runners.model.FrameworkMethod;
+import org.junit.runners.model.Statement;
+
+import org.apache.geode.cache.Cache;
+import org.apache.geode.cache.client.ClientCache;
+import org.apache.geode.cache.client.ClientCacheFactory;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.distributed.DistributedSystemDisconnectedException;
+import org.apache.geode.distributed.internal.DM;
+import org.apache.geode.distributed.internal.DistributionManager;
+import org.apache.geode.internal.cache.GemFireCacheImpl;
+import org.apache.geode.management.internal.SystemManagementService;
+import org.apache.geode.test.dunit.Invoke;
+import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
+import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
+import org.apache.geode.test.dunit.standalone.DUnitLauncher;
+
+/**
+ * Overriding MethodRule is only way to get {@code Object target}
+ */
+@SuppressWarnings("unused")
+public class ManagementTestRule implements MethodRule, Serializable {
+
+  public static Builder builder() {
+    return new Builder();
+  }
+
+  private final int managersCount;
+  private final int membersCount;
+  private final boolean start;
+  private final boolean managersFirst;
+  private final boolean createManagers;
+  private final boolean createMembers;
+
+  private JUnit4CacheTestCase helper;
+
+  private VM[] managers;
+  private VM[] members;
+
+  protected ManagementTestRule(final Builder builder) {
+    this.helper = new JUnit4CacheTestCase() {};
+    this.managersCount = builder.managersCount;
+    this.membersCount = builder.membersCount;
+    this.start = builder.start;
+    this.managersFirst = builder.managersFirst;
+    this.createManagers = builder.createManagers;
+    this.createMembers = builder.createMembers;
+  }
+
+  public DistributedMember getDistributedMember() {
+    return getCache().getDistributedSystem().getDistributedMember();
+  }
+
+  public DistributedMember getDistributedMember(final VM vm) {
+    return vm.invoke("getDistributedMember", () -> getDistributedMember());
+  }
+
+  public void createManagers() {
+    for (VM manager : this.managers) {
+      manager.invoke(() -> createManager(true));
+    }
+  }
+
+  public void createMembers() {
+    for (VM member : this.members) {
+      member.invoke(() -> createMember());
+    }
+  }
+
+  public void createManager() {
+    createManager(true);
+  }
+
+  public void createManager(final Properties properties) {
+    createManager(properties, true);
+  }
+
+  public void createManager(final boolean start) {
+    createManager(new Properties(), start);
+  }
+
+  public void createManager(final Properties properties, final boolean start) {
+    setPropertyIfNotSet(properties, JMX_MANAGER, "true");
+    setPropertyIfNotSet(properties, JMX_MANAGER_START, "false");
+    setPropertyIfNotSet(properties, JMX_MANAGER_PORT, "0");
+    setPropertyIfNotSet(properties, HTTP_SERVICE_PORT, "0");
+    setPropertyIfNotSet(properties, ENABLE_TIME_STATISTICS, "true");
+    setPropertyIfNotSet(properties, STATISTIC_SAMPLING_ENABLED, "true");
+
+    this.helper.getCache(properties);
+
+    if (start) {
+      startManager();
+    }
+  }
+
+  public void createManager(final VM managerVM) {
+    managerVM.invoke("createManager", () -> createManager());
+  }
+
+  public void createManager(final VM managerVM, final boolean start) {
+    managerVM.invoke("createManager", () -> createManager(start));
+  }
+
+  public void createManager(final VM managerVM, final Properties properties) {
+    managerVM.invoke("createManager", () -> createManager(properties, true));
+  }
+
+  public void createManager(final VM managerVM, final Properties properties, final boolean start) {
+    managerVM.invoke("createManager", () -> createManager(properties, start));
+  }
+
+  public void createMember() {
+    createMember(new Properties());
+  }
+
+  public void createMember(final Properties properties) {
+    setPropertyIfNotSet(properties, JMX_MANAGER, "false");
+    setPropertyIfNotSet(properties, ENABLE_TIME_STATISTICS, "true");
+    setPropertyIfNotSet(properties, STATISTIC_SAMPLING_ENABLED, "true");
+
+    System.out.println("KIRK: creating " + properties.getProperty(NAME));
+    this.helper.getCache(properties);
+  }
+
+  public void createMember(final VM memberVM) {
+    Properties properties = new Properties();
+    properties.setProperty(NAME, "memberVM-" + memberVM.getPid());
+    memberVM.invoke("createMember", () -> createMember(properties));
+  }
+
+  public void createMember(final VM memberVM, final Properties properties) throws Exception {
+    memberVM.invoke("createMember", () -> createMember(properties));
+  }
+
+  public Cache getCache() {
+    // Cache cache = GemFireCacheImpl.getInstance();
+    // if (cache != null && !cache.isClosed()) {
+    // return cache;
+    // }
+    return this.helper.getCache();
+  }
+
+  public ClientCache getClientCache() {
+    return this.helper.getClientCache(new ClientCacheFactory());
+  }
+
+  public boolean hasCache() {
+    // Cache cache = GemFireCacheImpl.getInstance();
+    // if (cache != null && !cache.isClosed()) {
+    // return true;
+    // }
+    return this.helper.hasCache();
+  }
+
+  public Cache basicGetCache() {
+    // Cache cache = GemFireCacheImpl.getInstance();
+    // if (cache != null && !cache.isClosed()) {
+    // return cache;
+    // }
+    return this.helper.basicGetCache();
+  }
+
+  public ManagementService getManagementService() {
+    assertThat(hasCache()).isTrue();
+    return ManagementService.getManagementService(basicGetCache());
+  }
+
+  public SystemManagementService getSystemManagementService() {
+    assertThat(hasCache()).isTrue();
+    return (SystemManagementService) ManagementService.getManagementService(basicGetCache());
+  }
+
+  public ManagementService getExistingManagementService() {
+    assertThat(hasCache()).isTrue();
+    return ManagementService.getExistingManagementService(basicGetCache());
+  }
+
+  public void startManager() {
+    SystemManagementService service = getSystemManagementService();
+    service.createManager();
+    service.startManager();
+  }
+
+  public void startManager(final VM managerVM) {
+    managerVM.invoke("startManager", () -> startManager());
+  }
+
+  public void stopManager() {
+    if (getManagementService().isManager()) {
+      getManagementService().stopManager();
+    }
+  }
+
+  public void stopManager(final VM managerVM) {
+    managerVM.invoke("stopManager", () -> stopManager());
+  }
+
+  public Set<DistributedMember> getOtherNormalMembers() {
+    Set<DistributedMember> allMembers = new HashSet<>(getAllNormalMembers());
+    allMembers.remove(getDistributedMember());
+    return allMembers;
+  }
+
+  public Set<DistributedMember> getAllNormalMembers() {
+    return getDistributionManager().getNormalDistributionManagerIds(); // excludes LOCATOR_DM_TYPE
+  }
+
+  private DM getDistributionManager() {
+    return ((GemFireCacheImpl) getCache()).getDistributionManager();
+  }
+
+  public void disconnectAllFromDS() {
+    stopManagerQuietly();
+    Invoke.invokeInEveryVM("stopManager", () -> stopManagerQuietly());
+    JUnit4DistributedTestCase.disconnectFromDS();
+    Invoke.invokeInEveryVM("disconnectFromDS", () -> JUnit4DistributedTestCase.disconnectFromDS());
+  }
+
+  private void setPropertyIfNotSet(final Properties properties, final String key,
+      final String value) {
+    if (!properties.containsKey(key)) {
+      properties.setProperty(key, value);
+    }
+  }
+
+  private void stopManagerQuietly() {
+    try {
+      if (hasCache() && !basicGetCache().isClosed()) {
+        stopManager();
+      }
+    } catch (DistributedSystemDisconnectedException | NullPointerException ignore) {
+    }
+  }
+
+  @Override
+  public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
+    return new Statement() {
+      @Override
+      public void evaluate() throws Throwable {
+        setUp(target);
+        try {
+          base.evaluate();
+        } finally {
+          tearDown();
+        }
+      }
+    };
+  }
+
+  private void setUp(final Object target) throws Exception {
+    DUnitLauncher.launchIfNeeded();
+    JUnit4DistributedTestCase.disconnectAllFromDS();
+
+    int whichVM = 0;
+
+    this.managers = new VM[this.managersCount];
+    for (int i = 0; i < this.managersCount; i++) {
+      this.managers[i] = getHost(0).getVM(whichVM);
+      whichVM++;
+    }
+
+    this.members = new VM[this.membersCount];
+    for (int i = 0; i < this.membersCount; i++) {
+      this.members[i] = getHost(0).getVM(whichVM);
+      whichVM++;
+    }
+
+    if (this.start) {
+      start();
+    }
+
+    processAnnotations(target);
+  }
+
+  private void start() {
+    if (this.createManagers && this.managersFirst) {
+      createManagers();
+    }
+    if (this.createMembers) {
+      createMembers();
+    }
+    if (this.createManagers && !this.managersFirst) {
+      createManagers();
+    }
+  }
+
+  private void tearDown() throws Exception {
+    JUnit4DistributedTestCase.disconnectAllFromDS();
+  }
+
+  private void processAnnotations(final Object target) {
+    try {
+      Class<?> clazz = target.getClass();
+
+      Field[] fields = clazz.getDeclaredFields();
+      for (Field field : fields) {
+        boolean alreadyAssigned = false;
+        for (Annotation annotation : field.getAnnotations()) {
+          if (annotation.annotationType().equals(Manager.class)) {
+            // annotated with @Manager
+            throwIfAlreadyAssigned(field, alreadyAssigned);
+            assignManagerField(target, field);
+            alreadyAssigned = true;
+          }
+          if (annotation.annotationType().equals(Member.class)) {
+            // annotated with @Manager
+            throwIfAlreadyAssigned(field, alreadyAssigned);
+            assignMemberField(target, field);
+            alreadyAssigned = true;
+          }
+        }
+      }
+    } catch (IllegalAccessException e) {
+      throw new Error(e);
+    }
+  }
+
+  private void throwIfAlreadyAssigned(final Field field, final boolean alreadyAssigned) {
+    if (alreadyAssigned) {
+      throw new IllegalStateException(
+          "Field " + field.getName() + " is already annotated with " + field.getAnnotations());
+    }
+  }
+
+  private void assignManagerField(final Object target, final Field field)
+      throws IllegalAccessException {
+    throwIfNotSameType(field, VM.class);
+
+    field.setAccessible(true);
+    if (field.getType().isArray()) {
+      field.set(target, this.managers);
+    } else {
+      field.set(target, this.managers[0]);
+    }
+  }
+
+  private void assignMemberField(final Object target, final Field field)
+      throws IllegalAccessException {
+    throwIfNotSameType(field, VM.class);
+
+    field.setAccessible(true);
+    if (field.getType().isArray()) {
+      field.set(target, this.members);
+    } else {
+      field.set(target, this.members[0]);
+    }
+  }
+
+  private void throwIfNotSameType(final Field field, final Class clazz) {
+    if (!field.getType().equals(clazz) && // non-array
+        !field.getType().getComponentType().equals(clazz)) { // array
+      throw new IllegalArgumentException(
+          "Field " + field.getName() + " is not same type as " + clazz.getName());
+    }
+  }
+
+  public static class Builder {
+
+    private boolean start = false;
+
+    private boolean createManagers = true;
+
+    private boolean createMembers = true;
+
+    private int managersCount = 1;
+
+    private int membersCount = 3;
+
+    private boolean managersFirst = true;
+
+    protected Builder() {}
+
+    public Builder createManagers(final boolean value) {
+      this.createManagers = value;
+      return this;
+    }
+
+    public Builder createMembers(final boolean value) {
+      this.createMembers = value;
+      return this;
+    }
+
+    public Builder withManagers(final int count) {
+      this.managersCount = count;
+      return this;
+    }
+
+    public Builder withMembers(final int count) {
+      this.membersCount = count;
+      return this;
+    }
+
+    public Builder managersFirst(final boolean value) {
+      this.managersFirst = value;
+      return this;
+    }
+
+    public Builder start(final boolean value) {
+      this.start = value;
+      return this;
+    }
+
+    public ManagementTestRule build() {
+      return new ManagementTestRule(this);
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/Manager.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/Manager.java b/geode-core/src/test/java/org/apache/geode/management/Manager.java
new file mode 100644
index 0000000..ce6c6a6
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/Manager.java
@@ -0,0 +1,29 @@
+/*
+ * 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.geode.management;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+@Target(FIELD)
+@Retention(RUNTIME)
+@Documented
+public @interface Manager {
+  String name() default "";
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/Member.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/Member.java b/geode-core/src/test/java/org/apache/geode/management/Member.java
new file mode 100644
index 0000000..84a80e5
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/Member.java
@@ -0,0 +1,29 @@
+/*
+ * 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.geode.management;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+@Target(FIELD)
+@Retention(RUNTIME)
+@Documented
+public @interface Member {
+  String name() default "";
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/OffHeapManagementDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/OffHeapManagementDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/OffHeapManagementDUnitTest.java
index 289d6d7..97fdab1 100644
--- a/geode-core/src/test/java/org/apache/geode/management/OffHeapManagementDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/OffHeapManagementDUnitTest.java
@@ -14,6 +14,7 @@
  */
 package org.apache.geode.management;
 
+import static com.jayway.awaitility.Awaitility.*;
 import static org.apache.geode.distributed.ConfigurationProperties.*;
 import static org.junit.Assert.*;
 
@@ -21,8 +22,11 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+
 import javax.management.Attribute;
 import javax.management.AttributeList;
+import javax.management.JMException;
 import javax.management.MBeanServer;
 import javax.management.Notification;
 import javax.management.NotificationListener;
@@ -36,31 +40,27 @@ import org.apache.geode.cache.Cache;
 import org.apache.geode.cache.DataPolicy;
 import org.apache.geode.cache.Region;
 import org.apache.geode.distributed.internal.InternalDistributedSystem;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.offheap.OffHeapMemoryStats;
 import org.apache.geode.internal.offheap.OffHeapStorage;
 import org.apache.geode.internal.offheap.OffHeapStoredObject;
 import org.apache.geode.management.internal.MBeanJMXAdapter;
 import org.apache.geode.management.internal.beans.MemberMBean;
 import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.SerializableCallable;
 import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
 import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
 import org.apache.geode.test.junit.categories.DistributedTest;
 
 /**
  * Tests the off-heap additions to the RegionMXBean and MemberMXBean JMX interfaces.
  */
-@SuppressWarnings("serial")
 @Category(DistributedTest.class)
+@SuppressWarnings("serial")
 public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
+
   /**
    * Specified assertion operations.
    */
-  private static enum ASSERT_OP {
+  private enum ASSERT_OP {
     EQUAL, GREATER_THAN, GREATER_THAN_OR_EQUAL, LESS_THAN
   }
 
@@ -139,28 +139,20 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   @Override
   public final void postSetUp() throws Exception {
-    Host.getHost(0).getVM(0).invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        System.setProperty(OffHeapStorage.STAY_CONNECTED_ON_OUTOFOFFHEAPMEMORY_PROPERTY, "true");
-      }
+    Host.getHost(0).getVM(0).invoke(() -> {
+      System.setProperty(OffHeapStorage.STAY_CONNECTED_ON_OUTOFOFFHEAPMEMORY_PROPERTY, "true");
     });
   }
 
   @Override
   public final void preTearDownCacheTestCase() throws Exception {
-    Host.getHost(0).getVM(0).invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        System.clearProperty(OffHeapStorage.STAY_CONNECTED_ON_OUTOFOFFHEAPMEMORY_PROPERTY);
-      }
+    Host.getHost(0).getVM(0).invoke(() -> {
+      System.clearProperty(OffHeapStorage.STAY_CONNECTED_ON_OUTOFOFFHEAPMEMORY_PROPERTY);
     });
   }
 
   /**
    * Tests off-heap additions to the RegionMXBean and MemberMXBean interfaces.
-   * 
-   * @throws Exception
    */
   @Test
   public void testOffHeapMBeanAttributesAndStats() throws Exception {
@@ -209,8 +201,6 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * Tests the fragmentation statistic for off-heap memory.
-   * 
-   * @throws Exception
    */
   @Test
   public void testFragmentationStat() throws Exception {
@@ -300,9 +290,7 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
   }
 
   /**
-   * Tests the compation time statistic for off-heap memory.
-   * 
-   * @throws Exception
+   * Tests the compaction time statistic for off-heap memory.
    */
   @Test
   public void testCompactionTimeStat() throws Exception {
@@ -476,12 +464,13 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * Destroys a number of entries previously allocated.
-   * 
+   *
    * @param vm a virtual machine
    * @param numAllocations the number of previous off-heap allocations
    * @param numDestroys the number of destroys to perform
    */
-  protected void doFreeOffHeapMemoryOnVm(VM vm, final int numAllocations, final int numDestroys) {
+  private void doFreeOffHeapMemoryOnVm(final VM vm, final int numAllocations,
+      final int numDestroys) {
     vm.invoke(new SerializableRunnable() {
       @Override
       public void run() {
@@ -492,11 +481,11 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * Performs some destroys to free off-heap allocations.
-   * 
+   *
    * @param numAllocations the number of previous off-heap allocations
    * @param numDestroys the number of destroys to perform
    */
-  protected void doFreeOffHeapMemory(int numAllocations, int numDestroys) {
+  private void doFreeOffHeapMemory(final int numAllocations, final int numDestroys) {
     assertTrue(numDestroys <= numAllocations);
 
     Region region = getCache().getRegion(OFF_HEAP_REGION_NAME);
@@ -520,34 +509,29 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * Consumes off off-heap memory until the allocation size cannot be satisfied.
-   * 
+   *
    * @param vm a virtual machine
    * @param allocationSize the number of bytes for each allocation
+   *
    * @return the number of successful puts
    */
-  protected int doConsumeOffHeapMemoryOnVm(VM vm, final int allocationSize) {
-    return (Integer) vm.invoke(new SerializableCallable() {
-      @Override
-      public Object call() {
-        return doConsumeOffHeapMemory(allocationSize);
-      }
-    });
+  private int doConsumeOffHeapMemoryOnVm(final VM vm, final int allocationSize) {
+    return vm.invoke(() -> doConsumeOffHeapMemory(allocationSize));
   }
 
   /**
    * Consumes off off-heap memory until the allocation size cannot be satisfied.
-   * 
+   *
    * @param allocationSize the number of bytes for each allocation
+   *
    * @return the number of successful puts
    */
-  protected int doConsumeOffHeapMemory(int allocationSize) { // TODO:KIRK: change this to handle new
-                                                             // OutOfOffHeapMemoryException
-    OffHeapMemoryStats stats = ((GemFireCacheImpl) getCache()).getOffHeapStore().getStats();
+  private int doConsumeOffHeapMemory(final int allocationSize) {
     int i = 0;
 
     // Loop until we fail
     try {
-      while (true) {
+      while (true) { // TODO: put a time limit on this just in case
         doPut("KEY" + (i++), new byte[allocationSize], OFF_HEAP_REGION_NAME, false);
       }
     } catch (OutOfOffHeapMemoryException e) {
@@ -558,28 +542,23 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * Asserts that the compactionTime stat is available and satisfies an assert operation.
-   * 
+   *
    * @param vm a virtual machine.
    * @param compactionTime total off heap compaction time.
    * @param op an assert operation.
    */
-  protected void assertCompactionTimeStatOnVm(VM vm, final long compactionTime,
+  private void assertCompactionTimeStatOnVm(final VM vm, final long compactionTime,
       final ASSERT_OP op) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        assertCompactionTimeStat(compactionTime, op);
-      }
-    });
+    vm.invoke(() -> assertCompactionTimeStat(compactionTime, op));
   }
 
   /**
    * Asserts that the compactionTime stat is available and satisfies an assert operation.
-   * 
+   *
    * @param compactionTime total off heap compaction time.
    * @param op an assert operation.
    */
-  protected void assertCompactionTimeStat(long compactionTime, ASSERT_OP op) {
+  private void assertCompactionTimeStat(final long compactionTime, final ASSERT_OP op) {
     ManagementService service = ManagementService.getExistingManagementService(getCache());
     assertNotNull(service);
 
@@ -606,27 +585,23 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * Asserts that the fragmentation stat is available and satisfies an assert operation.
-   * 
+   *
    * @param vm a virtual machine
    * @param fragmentation a fragmentation percentage
    * @param op an assertion operation
    */
-  protected void assertFragmentationStatOnVm(VM vm, final int fragmentation, final ASSERT_OP op) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        assertFragmentationStat(fragmentation, op);
-      }
-    });
+  private void assertFragmentationStatOnVm(final VM vm, final int fragmentation,
+      final ASSERT_OP op) {
+    vm.invoke(() -> assertFragmentationStat(fragmentation, op));
   }
 
   /**
    * Asserts that the fragmentation stat is available and satisfies an assert operation.
-   * 
+   *
    * @param fragmentation a fragmentation percentage
    * @param op an assertion operation
    */
-  protected void assertFragmentationStat(int fragmentation, ASSERT_OP op) {
+  private void assertFragmentationStat(final int fragmentation, final ASSERT_OP op) {
     ManagementService service = ManagementService.getExistingManagementService(getCache());
     assertNotNull(service);
 
@@ -651,7 +626,7 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
   /**
    * Returns off-heap system properties for enabling off-heap and the JMX system.
    */
-  protected Properties getSystemProperties() {
+  private Properties getSystemProperties() {
     Properties props = getDistributedSystemProperties();
 
     props.setProperty(OFF_HEAP_MEMORY_SIZE, "1m");
@@ -664,16 +639,11 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * Removes off heap region on vm and disconnects.
-   * 
-   * @param vm a virutal machine.
+   *
+   * @param vm a virtual machine.
    */
-  protected void doCleanupOnVm(VM vm) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        cleanup();
-      }
-    });
+  private void doCleanupOnVm(final VM vm) {
+    vm.invoke(() -> cleanup());
   }
 
   /**
@@ -696,20 +666,14 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
   /**
    * Asserts that the off heap region data is available and enabled for a VM.
    */
-  @SuppressWarnings("serial")
-  protected void assertOffHeapRegionAttributesOnVm(VM vm) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        assertOffHeapRegionAttributes();
-      }
-    });
+  private void assertOffHeapRegionAttributesOnVm(final VM vm) {
+    vm.invoke(() -> assertOffHeapRegionAttributes());
   }
 
   /**
    * Asserts that the off heap region data is available and enabled.
    */
-  protected void assertOffHeapRegionAttributes() {
+  private void assertOffHeapRegionAttributes() {
     ManagementService service = ManagementService.getExistingManagementService(getCache());
     assertNotNull(service);
 
@@ -726,33 +690,28 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * Asserts that OffHeapMetrics match input parameters for a VM.
-   * 
+   *
    * @param vm a virtual machine.
    * @param freeMemory total off-heap free memory in bytes.
    * @param allocatedMemory allocated (or used) off-heap memory in bytes.
    * @param objects number of objects stored in off-heap memory.
    * @param fragmentation the fragmentation percentage.
    */
-  protected void assertOffHeapMetricsOnVm(VM vm, final long freeMemory, final long allocatedMemory,
-      final long objects, final int fragmentation) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        assertOffHeapMetrics(freeMemory, allocatedMemory, objects, fragmentation);
-      }
-    });
+  private void assertOffHeapMetricsOnVm(final VM vm, final long freeMemory,
+      final long allocatedMemory, final long objects, final int fragmentation) {
+    vm.invoke(() -> assertOffHeapMetrics(freeMemory, allocatedMemory, objects, fragmentation));
   }
 
   /**
    * Asserts that OffHeapMetrics match input parameters.
-   * 
+   *
    * @param freeMemory total off-heap free memory in bytes.
    * @param allocatedMemory allocated (or used) off-heap memory in bytes.
    * @param objects number of objects stored in off-heap memory.
    * @param fragmentation the fragmentation percentage.
    */
-  protected void assertOffHeapMetrics(long freeMemory, long allocatedMemory, long objects,
-      int fragmentation) {
+  private void assertOffHeapMetrics(final long freeMemory, final long allocatedMemory,
+      final long objects, final int fragmentation) {
     ManagementService service = ManagementService.getExistingManagementService(getCache());
     assertNotNull(service);
 
@@ -769,57 +728,49 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * Creates an off-heap region on a vm.
-   * 
+   *
    * @param vm a virtual machine.
    * @param name a region name.
    * @param dataPolicy a data policy.
+   *
    * @return true if successful.
    */
-  protected boolean createOffHeapRegionOnVm(final VM vm, final String name,
+  private boolean createOffHeapRegionOnVm(final VM vm, final String name,
       final DataPolicy dataPolicy) {
-    return (Boolean) vm.invoke(new SerializableCallable() {
-      @Override
-      public Object call() throws Exception {
-        return (null != createOffHeapRegion(name, dataPolicy));
-      }
-    });
+    return vm.invoke(() -> null != createOffHeapRegion(name, dataPolicy));
   }
 
   /**
    * Creates an off-heap region.
-   * 
+   *
    * @param name a region name.
    * @param dataPolicy a data policy.
+   *
    * @return the newly created region.
    */
-  protected Region createOffHeapRegion(String name, DataPolicy dataPolicy) {
+  private Region createOffHeapRegion(final String name, final DataPolicy dataPolicy) {
     return getCache().createRegionFactory().setOffHeap(true).setDataPolicy(dataPolicy).create(name);
   }
 
   /**
    * Sets the distributed system properties for a vm.
-   * 
+   *
    * @param vm a virtual machine.
    * @param management starts the ManagementService when true.
    * @param props distributed system properties.
    */
-  @SuppressWarnings("serial")
-  protected void setSystemPropertiesOnVm(VM vm, final boolean management, final Properties props) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        setSystemProperties(management, props);
-      }
-    });
+  private void setSystemPropertiesOnVm(final VM vm, final boolean management,
+      final Properties props) {
+    vm.invoke(() -> setSystemProperties(management, props));
   }
 
   /**
    * Sets the distributed system properties.
-   * 
+   *
    * @param management starts the ManagementService when true.
    * @param props distributed system properties.
    */
-  protected void setSystemProperties(boolean management, Properties props) {
+  private void setSystemProperties(final boolean management, final Properties props) {
     getSystem(props);
 
     if (management) {
@@ -832,27 +783,22 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * Performs a destroy operation on a vm.
-   * 
+   *
    * @param vm a virtual machine.
    * @param key the region entry to destroy.
    * @param regionName a region name.
    */
-  protected void doDestroyOnVm(final VM vm, final Object key, final String regionName) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        doDestroy(key, regionName);
-      }
-    });
+  private void doDestroyOnVm(final VM vm, final Object key, final String regionName) {
+    vm.invoke(() -> doDestroy(key, regionName));
   }
 
   /**
    * Performs a destroy operation.
-   * 
+   *
    * @param key the region entry to destroy.
    * @param regionName a region name.
    */
-  protected void doDestroy(Object key, String regionName) {
+  private void doDestroy(final Object key, final String regionName) {
     Region region = getCache().getRegion(regionName);
     assertNotNull(region);
 
@@ -861,59 +807,54 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * Performs a put operation on a vm.
-   * 
+   *
    * @param vm a virtual machine.
    * @param key region entry key.
    * @param value region entry value.
    * @param regionName a region name.
    */
-  protected void doPutOnVm(final VM vm, final Object key, final Object value,
-      final String regionName, final boolean expectException) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        doPut(key, value, regionName, expectException);
-      }
-    });
+  private void doPutOnVm(final VM vm, final Object key, final Object value, final String regionName,
+      final boolean expectException) {
+    vm.invoke(() -> doPut(key, value, regionName, expectException));
   }
 
   /**
    * Performs a put operation.
-   * 
+   *
    * @param key region entry key.
    * @param value region entry value.
    * @param regionName a region name.
    */
-  protected void doPut(Object key, Object value, String regionName, boolean expectException) {
+  private void doPut(final Object key, final Object value, final String regionName,
+      final boolean expectException) {
     Region region = getCache().getRegion(regionName);
     assertNotNull(region);
 
     try {
       region.put(key, value);
+      if (expectException) {
+        fail("Expected OutOfOffHeapMemoryException");
+      }
     } catch (OutOfOffHeapMemoryException e) {
-      if (!expectException)
+      if (!expectException) {
         throw e;
+      }
     }
   }
 
   /**
    * Adds an off-heap notification listener to the MemberMXBean for a vm.
-   * 
+   *
    * @param vm a virtual machine.
    */
-  protected void addOffHeapNotificationListenerOnVm(VM vm) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        addOffHeapNotificationListener();
-      }
-    });
+  private void addOffHeapNotificationListenerOnVm(final VM vm) {
+    vm.invoke(() -> addOffHeapNotificationListener());
   }
 
   /**
    * Adds an off-heap notification listener to the MemberMXBean.
    */
-  protected void addOffHeapNotificationListener() {
+  private void addOffHeapNotificationListener() {
     ManagementService service = ManagementService.getExistingManagementService(getCache());
     assertNotNull(service);
 
@@ -929,116 +870,90 @@ public class OffHeapManagementDUnitTest extends JUnit4CacheTestCase {
 
   /**
    * Creates and adds a generic GaugeMonitor for an attribute of the MemberMXBean on a VM.
-   * 
+   *
    * @param vm a virtual machine.
    * @param attribute the attribute to monitor.
    * @param highThreshold the high threshold trigger.
    * @param lowThreshold the low threshold trigger.
    */
-  protected void setupOffHeapMonitorOnVm(VM vm, final String attribute, final long highThreshold,
-      final long lowThreshold) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        setupOffHeapMonitor(attribute, highThreshold, lowThreshold);
-      }
-    });
+  private void setupOffHeapMonitorOnVm(final VM vm, final String attribute,
+      final long highThreshold, final long lowThreshold) {
+    vm.invoke(() -> setupOffHeapMonitor(attribute, highThreshold, lowThreshold));
   }
 
   /**
    * Creates and adds a generic GaugeMonitor for an attribute of the MemberMXBean.
-   * 
+   *
    * @param attribute the attribute to monitor.
    * @param highThreshold the high threshold trigger.
    * @param lowThreshold the low threshold trigger.
    */
-  protected void setupOffHeapMonitor(String attribute, long highThreshold, long lowThreshold) {
+  private void setupOffHeapMonitor(final String attribute, final long highThreshold,
+      final long lowThreshold) throws JMException {
     ObjectName memberMBeanObjectName = MBeanJMXAdapter.getMemberMBeanName(
         InternalDistributedSystem.getConnectedInstance().getDistributedMember());
     assertNotNull(memberMBeanObjectName);
 
-    try {
-      ObjectName offHeapMonitorName = new ObjectName("monitors:type=Gauge,attr=" + attribute);
-      mbeanServer.createMBean("javax.management.monitor.GaugeMonitor", offHeapMonitorName);
-
-      AttributeList al = new AttributeList();
-      al.add(new Attribute("ObservedObject", memberMBeanObjectName));
-      al.add(new Attribute("GranularityPeriod", 500));
-      al.add(new Attribute("ObservedAttribute", attribute));
-      al.add(new Attribute("Notify", true));
-      al.add(new Attribute("NotifyHigh", true));
-      al.add(new Attribute("NotifyLow", true));
-      al.add(new Attribute("HighTheshold", highThreshold));
-      al.add(new Attribute("LowThreshold", lowThreshold));
-
-      mbeanServer.setAttributes(offHeapMonitorName, al);
-      mbeanServer.addNotificationListener(offHeapMonitorName, notificationListener, null, null);
-      mbeanServer.invoke(offHeapMonitorName, "start", new Object[] {}, new String[] {});
-    } catch (Exception e) {
-      fail(e.getMessage());
-    }
+    ObjectName offHeapMonitorName = new ObjectName("monitors:type=Gauge,attr=" + attribute);
+    mbeanServer.createMBean("javax.management.monitor.GaugeMonitor", offHeapMonitorName);
+
+    AttributeList al = new AttributeList();
+    al.add(new Attribute("ObservedObject", memberMBeanObjectName));
+    al.add(new Attribute("GranularityPeriod", 500));
+    al.add(new Attribute("ObservedAttribute", attribute));
+    al.add(new Attribute("Notify", true));
+    al.add(new Attribute("NotifyHigh", true));
+    al.add(new Attribute("NotifyLow", true));
+    al.add(new Attribute("HighTheshold", highThreshold));
+    al.add(new Attribute("LowThreshold", lowThreshold));
+
+    mbeanServer.setAttributes(offHeapMonitorName, al);
+    mbeanServer.addNotificationListener(offHeapMonitorName, notificationListener, null, null);
+    mbeanServer.invoke(offHeapMonitorName, "start", new Object[] {}, new String[] {});
   }
 
   /**
    * Waits to receive MBean notifications.
-   * 
+   *
    * @param vm a virtual machine.
    * @param wait how long to wait for in millis.
    * @param interval the polling interval to check for notifications.
    * @param throwOnTimeout throws an exception on timeout if true.
    */
-  protected void waitForNotificationListenerOnVm(VM vm, final long wait, final long interval,
+  private void waitForNotificationListenerOnVm(final VM vm, final long wait, final long interval,
       final boolean throwOnTimeout) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        Wait.waitForCriterion(new WaitCriterion() {
-          @Override
-          public boolean done() {
-            return (notificationListener.getNotificationSize() > 0);
-          }
-
-          @Override
-          public String description() {
-            return "Awaiting Notification Listener";
-          }
-        }, wait, interval, throwOnTimeout);
-      }
-    });
+    vm.invoke(() -> await("Awaiting Notification Listener").atMost(wait, TimeUnit.MILLISECONDS)
+        .until(() -> assertTrue(notificationListener.getNotificationSize() > 0)));
   }
 
   /**
    * Clears received notifications.
-   * 
+   *
    * @param vm a virtual machine.
    */
-  protected void clearNotificationListenerOnVm(VM vm) {
-    vm.invoke(new SerializableRunnable() {
-      @Override
-      public void run() {
-        notificationListener.clear();
-      }
-    });
+  private void clearNotificationListenerOnVm(final VM vm) {
+    vm.invoke(() -> notificationListener.clear());
   }
-}
 
+  /**
+   * Collects MBean Notifications.
+   */
+  private static class OffHeapNotificationListener implements NotificationListener {
 
-/**
- * Collects MBean Notifications.
- */
-class OffHeapNotificationListener implements NotificationListener {
-  List<Notification> notificationList = Collections.synchronizedList(new ArrayList<Notification>());
+    List<Notification> notificationList =
+        Collections.synchronizedList(new ArrayList<Notification>());
 
-  @Override
-  public void handleNotification(Notification notification, Object handback) {
-    this.notificationList.add(notification);
-  }
+    @Override
+    public void handleNotification(final Notification notification, final Object handback) {
+      this.notificationList.add(notification);
+    }
 
-  public void clear() {
-    this.notificationList.clear();
-  }
+    public void clear() {
+      this.notificationList.clear();
+    }
 
-  public int getNotificationSize() {
-    return this.notificationList.size();
+    public int getNotificationSize() {
+      return this.notificationList.size();
+    }
   }
 }


[2/8] geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/bean/stats/DistributedSystemStatsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/bean/stats/DistributedSystemStatsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/bean/stats/DistributedSystemStatsDUnitTest.java
index d2e797e..63cf88f 100644
--- a/geode-core/src/test/java/org/apache/geode/management/bean/stats/DistributedSystemStatsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/bean/stats/DistributedSystemStatsDUnitTest.java
@@ -14,98 +14,70 @@
  */
 package org.apache.geode.management.bean.stats;
 
-import org.junit.experimental.categories.Category;
-import org.junit.Test;
-
+import static com.jayway.awaitility.Awaitility.*;
 import static org.junit.Assert.*;
 
-import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
-import org.apache.geode.test.junit.categories.DistributedTest;
-
+import java.lang.management.ManagementFactory;
 import java.util.Set;
+import java.util.concurrent.TimeUnit;
 
 import javax.management.ObjectName;
 
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
 import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.DiskStoreStats;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.management.DistributedSystemMXBean;
-import org.apache.geode.management.ManagementTestBase;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.ManagementTestRule;
+import org.apache.geode.management.Manager;
+import org.apache.geode.management.Member;
 import org.apache.geode.management.MemberMXBean;
 import org.apache.geode.management.internal.SystemManagementService;
-import org.apache.geode.management.internal.beans.MemberMBean;
-import org.apache.geode.management.internal.beans.MemberMBeanBridge;
-import org.apache.geode.test.dunit.Assert;
-import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.junit.categories.DistributedTest;
 
-/**
- */
 @Category(DistributedTest.class)
-public class DistributedSystemStatsDUnitTest extends ManagementTestBase {
+@SuppressWarnings("serial")
+public class DistributedSystemStatsDUnitTest {
 
-  private static final long serialVersionUID = 1L;
+  @Manager
+  private VM manager;
 
-  public DistributedSystemStatsDUnitTest() {
-    super();
-  }
+  @Member
+  private VM[] members;
+
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().build();
 
   @Test
   public void testDistributedSystemStats() throws Exception {
-    initManagement(true);
-
-    for (VM vm : managedNodeList) {
-      setDiskStats(vm);
-    }
-    verifyDiskStats(managingNode);
-  }
-
-  @SuppressWarnings("serial")
-  public void setDiskStats(VM vm1) throws Exception {
-    vm1.invoke(new SerializableRunnable("Set Member Stats") {
-      public void run() {
-        MemberMBean bean = (MemberMBean) managementService.getMemberMXBean();
-        MemberMBeanBridge bridge = bean.getBridge();
-        DiskStoreStats diskStoreStats = new DiskStoreStats(basicGetSystem(), "test");
-        bridge.addDiskStoreStats(diskStoreStats);
-        diskStoreStats.startRead();
-        diskStoreStats.startWrite();
-        diskStoreStats.startBackup();
-        diskStoreStats.startRecovery();
-        diskStoreStats.incWrittenBytes(20, true);
-        diskStoreStats.startFlush();
-        diskStoreStats.setQueueSize(10);
-      }
-    });
-  }
-
-  @SuppressWarnings("serial")
-  public void verifyDiskStats(VM vm1) throws Exception {
-    vm1.invoke(new SerializableRunnable("Set Member Stats") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        DistributedSystemMXBean bean = service.getDistributedSystemMXBean();
-        assertNotNull(bean);
-        Set<DistributedMember> otherMemberSet =
-            cache.getDistributionManager().getOtherNormalDistributionManagerIds();
-
-        for (DistributedMember member : otherMemberSet) {
-          ObjectName memberMBeanName;
-          try {
-            memberMBeanName = service.getMemberMBeanName(member);
-            waitForProxy(memberMBeanName, MemberMXBean.class);
-            MemberMXBean memberBean = service.getMBeanProxy(memberMBeanName, MemberMXBean.class);
-            waitForRefresh(2, memberMBeanName);
-          } catch (NullPointerException e) {
-            Assert.fail("FAILED WITH EXCEPION", e);
-          } catch (Exception e) {
-            Assert.fail("FAILED WITH EXCEPION", e);
-          }
-        }
-
+    this.manager.invoke("verifyMBeans", () -> {
+      GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+      assertNotNull(cache);
+
+      SystemManagementService service =
+          (SystemManagementService) ManagementService.getManagementService(cache);
+      DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+      assertNotNull(distributedSystemMXBean);
+
+      Set<DistributedMember> otherMemberSet =
+          cache.getDistributionManager().getOtherNormalDistributionManagerIds();
+      assertEquals(3, otherMemberSet.size());
+
+      for (DistributedMember member : otherMemberSet) {
+        ObjectName memberMXBeanName = service.getMemberMBeanName(member);
+        await().atMost(2, TimeUnit.MINUTES).until(() -> assertTrue(
+            ManagementFactory.getPlatformMBeanServer().isRegistered(memberMXBeanName)));
+
+        MemberMXBean memberMXBean = service.getMBeanProxy(memberMXBeanName, MemberMXBean.class);
+        assertNotNull(memberMXBean);
+
+        final long lastRefreshTime = service.getLastUpdateTime(memberMXBeanName);
+        await().atMost(1, TimeUnit.MINUTES)
+            .until(() -> assertTrue(service.getLastUpdateTime(memberMXBeanName) > lastRefreshTime));
       }
     });
   }

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/internal/beans/QueryDataFunctionApplyLimitClauseTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/beans/QueryDataFunctionApplyLimitClauseTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/beans/QueryDataFunctionApplyLimitClauseTest.java
index f4ca239..dcfd2bf 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/beans/QueryDataFunctionApplyLimitClauseTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/beans/QueryDataFunctionApplyLimitClauseTest.java
@@ -24,7 +24,6 @@ import org.junit.experimental.categories.Category;
 
 import org.apache.geode.test.junit.categories.UnitTest;
 
-
 @Category(UnitTest.class)
 public class QueryDataFunctionApplyLimitClauseTest {
 

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestClientIdsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestClientIdsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestClientIdsDUnitTest.java
index 9416616..a7940a4 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestClientIdsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestClientIdsDUnitTest.java
@@ -14,11 +14,22 @@
  */
 package org.apache.geode.management.internal.pulse;
 
+import static java.util.concurrent.TimeUnit.MINUTES;
 import static org.apache.geode.distributed.ConfigurationProperties.*;
+import static org.apache.geode.test.dunit.NetworkUtils.getServerHostName;
+import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.Assert.*;
 
+import java.io.IOException;
+import java.io.Serializable;
 import java.util.Properties;
 
+import javax.management.ObjectName;
+
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
+import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
@@ -29,273 +40,141 @@ import org.apache.geode.cache.DataPolicy;
 import org.apache.geode.cache.Region;
 import org.apache.geode.cache.RegionAttributes;
 import org.apache.geode.cache.Scope;
+import org.apache.geode.cache.client.ClientCache;
+import org.apache.geode.cache.client.ClientRegionFactory;
+import org.apache.geode.cache.client.ClientRegionShortcut;
 import org.apache.geode.cache.client.PoolManager;
 import org.apache.geode.cache.client.internal.PoolImpl;
 import org.apache.geode.cache.server.CacheServer;
 import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.DistributedSystem;
-import org.apache.geode.internal.AvailablePort;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.management.CacheServerMXBean;
-import org.apache.geode.management.MBeanUtil;
-import org.apache.geode.management.ManagementTestBase;
-import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.ManagementTestRule;
+import org.apache.geode.management.Manager;
+import org.apache.geode.management.internal.SystemManagementService;
 import org.apache.geode.test.dunit.Assert;
 import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.LogWriterUtils;
-import org.apache.geode.test.dunit.NetworkUtils;
 import org.apache.geode.test.dunit.SerializableCallable;
 import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
 import org.apache.geode.test.junit.categories.DistributedTest;
 
 /**
  * This is for testing client IDs
  */
 @Category(DistributedTest.class)
-public class TestClientIdsDUnitTest extends JUnit4DistributedTestCase {
-
-  private static final String k1 = "k1";
-  private static final String k2 = "k2";
-
-  private static final String client_k1 = "client-k1";
-
-  private static final String client_k2 = "client-k2";
-
-  /** name of the test region */
-  private static final String REGION_NAME = "ClientHealthStatsDUnitTest_Region";
-
-  private static VM server = null;
-
-  private static VM client = null;
-
-  private static VM client2 = null;
-
-  private static VM managingNode = null;
-
-  private ManagementTestBase helper;
-
-  @Override
-  public final void preSetUp() throws Exception {
-    this.helper = new ManagementTestBase() {};
-  }
-
-  @Override
-  public final void postSetUp() throws Exception {
-    final Host host = Host.getHost(0);
-    managingNode = host.getVM(0);
-    server = host.getVM(1);
-    client = host.getVM(2);
-    client2 = host.getVM(3);
-  }
-
-  @Override
-  public final void preTearDown() throws Exception {
-    helper.closeCache(managingNode);
-    helper.closeCache(server);
-    helper.closeCache(client);
-    helper.closeCache(client2);
-
-    disconnectFromDS();
+@SuppressWarnings({"serial", "unused"})
+public class TestClientIdsDUnitTest implements Serializable {
+
+  private static final String KEY1 = "KEY1";
+  private static final String KEY2 = "KEY2";
+  private static final String VALUE1 = "client-KEY1";
+  private static final String VALUE2 = "client-KEY2";
+  private static final String REGION_NAME =
+      TestClientIdsDUnitTest.class.getSimpleName() + "_Region";
+
+  @Manager
+  private VM managerVM;
+
+  private VM serverVM;
+  private VM client1VM;
+  private VM client2VM;
+
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().start(false).build();
+
+  @Before
+  public void before() throws Exception {
+    serverVM = Host.getHost(0).getVM(1);
+    client1VM = Host.getHost(0).getVM(2);
+    client2VM = Host.getHost(0).getVM(3);
   }
 
   @Test
   public void testClientIds() throws Exception {
-    helper.createManagementCache(managingNode);
-    helper.startManagingNode(managingNode);
-    int port = (Integer) createServerCache(server);
-    DistributedMember serverMember = helper.getMember(server);
-    createClientCache(client, NetworkUtils.getServerHostName(server.getHost()), port);
-    createClientCache(client2, NetworkUtils.getServerHostName(server.getHost()), port);
-    put(client);
-    put(client2);
-    verifyClientIds(managingNode, serverMember, port);
-    helper.stopManagingNode(managingNode);
-  }
+    this.managementTestRule.createManagers();
 
-  @SuppressWarnings("serial")
-  private Object createServerCache(VM vm) {
-    return vm.invoke(new SerializableCallable("Create Server Cache") {
-      public Object call() {
-        try {
-          return createServerCache();
-        } catch (Exception e) {
-          fail("Error while createServerCache " + e);
-        }
-        return null;
-      }
-    });
-  }
+    int port = this.serverVM.invoke(() -> createServerCache());
+
+    this.client1VM
+        .invoke(() -> createClientCache(getServerHostName(this.serverVM.getHost()), port));
+    this.client2VM
+        .invoke(() -> createClientCache(getServerHostName(this.serverVM.getHost()), port));
 
-  @SuppressWarnings("serial")
-  private void createClientCache(VM vm, final String host, final Integer port1) {
-    vm.invoke(new SerializableCallable("Create Client Cache") {
+    DistributedMember serverMember = this.managementTestRule.getDistributedMember(this.serverVM);
+    DistributedMember client1Member = this.managementTestRule.getDistributedMember(this.client1VM);
+    DistributedMember client2Member = this.managementTestRule.getDistributedMember(this.client2VM);
 
-      public Object call() {
+    // this.managerVM.invoke(() -> verifyClientIds(serverMember, port));
+    this.managerVM.invoke(() -> {
+      CacheServerMXBean cacheServerMXBean = awaitCacheServerMXBean(serverMember, port);
+      await().until(() -> {
         try {
-          createClientCache(host, port1);
+          assertThat(cacheServerMXBean.getClientIds()).hasSize(2);
         } catch (Exception e) {
-          fail("Error while createClientCache " + e);
+          throw new Error(e);
         }
-        return null;
-      }
+      });
+      assertThat(cacheServerMXBean.getClientIds()).hasSize(2); // TODO
     });
   }
 
-  private Cache createCache(Properties props) throws Exception {
-    DistributedSystem ds = getSystem(props);
-    ds.disconnect();
-    ds = getSystem(props);
-    assertNotNull(ds);
-    Cache cache = (GemFireCacheImpl) CacheFactory.create(ds);
-    assertNotNull(cache);
-    return cache;
-  }
+  private int createServerCache() throws IOException {
+    Cache cache = this.managementTestRule.getCache();
 
-  private Integer createServerCache(DataPolicy dataPolicy) throws Exception {
-    Cache cache = helper.createCache(false);
     AttributesFactory factory = new AttributesFactory();
     factory.setScope(Scope.DISTRIBUTED_ACK);
-    factory.setDataPolicy(dataPolicy);
+    factory.setDataPolicy(DataPolicy.REPLICATE);
+
     RegionAttributes attrs = factory.create();
     cache.createRegion(REGION_NAME, attrs);
-    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
-    CacheServer server1 = cache.addCacheServer();
-    server1.setPort(port);
-    server1.setNotifyBySubscription(true);
-    server1.start();
-    return new Integer(server1.getPort());
-  }
 
-  public Integer createServerCache() throws Exception {
-    return createServerCache(DataPolicy.REPLICATE);
+    CacheServer cacheServer = cache.addCacheServer();
+    cacheServer.setPort(0);
+    cacheServer.setNotifyBySubscription(true);
+    cacheServer.start();
+    return cacheServer.getPort();
   }
 
-  public Cache createClientCache(String host, Integer port1) throws Exception {
+  private void createClientCache(final String host, final int serverPort) {
+    ClientCache cache = this.managementTestRule.getClientCache();
 
-    Properties props = new Properties();
-    props.setProperty(MCAST_PORT, "0");
-    props.setProperty(LOCATORS, "");
-    Cache cache = createCache(props);
-    PoolImpl p = (PoolImpl) PoolManager.createFactory().addServer(host, port1.intValue())
+    PoolImpl pool = (PoolImpl) PoolManager.createFactory().addServer(host, serverPort)
         .setSubscriptionEnabled(false).setThreadLocalConnections(true).setMinConnections(1)
         .setReadTimeout(20000).setPingInterval(10000).setRetryAttempts(1)
-        .setSubscriptionEnabled(true).setStatisticInterval(1000)
-        .create("CacheServerManagementDUnitTest");
-
-    AttributesFactory factory = new AttributesFactory();
-    factory.setScope(Scope.DISTRIBUTED_ACK);
-    factory.setPoolName(p.getName());
-
-    RegionAttributes attrs = factory.create();
-    Region region = cache.createRegion(REGION_NAME, attrs);
-    return cache;
+        .setSubscriptionEnabled(true).setStatisticInterval(1000).create(getClass().getSimpleName());
 
+    ClientRegionFactory factory =
+        cache.createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY);
+    factory.setPoolName(pool.getName());
+    factory.create(REGION_NAME);
   }
 
-  /**
-   * get member id
-   */
-  @SuppressWarnings("serial")
-  protected static DistributedMember getMember() throws Exception {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    return cache.getDistributedSystem().getDistributedMember();
+  private void verifyClientIds(final DistributedMember serverMember, final int serverPort)
+      throws Exception {
+    CacheServerMXBean cacheServerMXBean = awaitCacheServerMXBean(serverMember, serverPort);
+    await().until(() -> {
+      try {
+        assertThat(cacheServerMXBean.getClientIds()).hasSize(2);
+      } catch (Exception e) {
+        throw new Error(e);
+      }
+    });
+    assertThat(cacheServerMXBean.getClientIds()).hasSize(2); // TODO
   }
 
-  /**
-   * Verify the Cache Server details
-   * 
-   * @param vm
-   */
-  @SuppressWarnings("serial")
-  protected void verifyClientIds(final VM vm, final DistributedMember serverMember,
-      final int serverPort) {
-    SerializableRunnable verifyCacheServerRemote =
-        new SerializableRunnable("Verify Cache Server Remote") {
-          public void run() {
-            try {
-              final WaitCriterion waitCriteria = new WaitCriterion() {
-                @Override
-                public boolean done() {
-                  CacheServerMXBean bean = null;
-                  try {
-                    bean = MBeanUtil.getCacheServerMbeanProxy(serverMember, serverPort);
-                    if (bean != null) {
-                      if (bean.getClientIds().length > 0) {
-                        return true;
-                      }
-                    }
-                  } catch (Exception e) {
-                    LogWriterUtils.getLogWriter().info("exception occured " + e.getMessage()
-                        + CliUtil.stackTraceAsString((Throwable) e));
-                  }
-                  return false;
-                }
+  private CacheServerMXBean awaitCacheServerMXBean(final DistributedMember serverMember,
+      final int port) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    ObjectName objectName = service.getCacheServerMBeanName(port, serverMember);
 
-                @Override
-                public String description() {
-                  return "wait for getNumOfClients bean to complete and get results";
-                }
-              };
-              Wait.waitForCriterion(waitCriteria, 2 * 60 * 1000, 3000, true);
+    await().until(
+        () -> assertThat(service.getMBeanProxy(objectName, CacheServerMXBean.class)).isNotNull());
 
-              // Now it is sure that bean would be available
-              CacheServerMXBean bean = MBeanUtil.getCacheServerMbeanProxy(serverMember, serverPort);
-              LogWriterUtils.getLogWriter().info("verifyClientIds = " + bean.getClientIds().length);
-              assertEquals(true, bean.getClientIds().length > 0 ? true : false);
-            } catch (Exception e) {
-              fail("Error while verifying cache server from remote member " + e);
-            }
-          }
-        };
-    vm.invoke(verifyCacheServerRemote);
+    return service.getMBeanProxy(objectName, CacheServerMXBean.class);
   }
 
-  /**
-   * Verify the Cache Server details
-   * 
-   * @param vm
-   */
-  @SuppressWarnings("serial")
-  protected void put(final VM vm) {
-    SerializableRunnable put = new SerializableRunnable("put") {
-      public void run() {
-        try {
-          Cache cache = GemFireCacheImpl.getInstance();
-          Region<Object, Object> r1 = cache.getRegion(Region.SEPARATOR + REGION_NAME);
-          assertNotNull(r1);
-
-          r1.put(k1, client_k1);
-          assertEquals(r1.getEntry(k1).getValue(), client_k1);
-          r1.put(k2, client_k2);
-          assertEquals(r1.getEntry(k2).getValue(), client_k2);
-          try {
-            Thread.sleep(10000);
-          } catch (Exception e) {
-            // sleep
-          }
-          r1.clear();
-
-          r1.put(k1, client_k1);
-          assertEquals(r1.getEntry(k1).getValue(), client_k1);
-          r1.put(k2, client_k2);
-          assertEquals(r1.getEntry(k2).getValue(), client_k2);
-          try {
-            Thread.sleep(10000);
-          } catch (Exception e) {
-            // sleep
-          }
-          r1.clear();
-        } catch (Exception ex) {
-          Assert.fail("failed while put", ex);
-        }
-      }
-
-    };
-    vm.invoke(put);
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(2, MINUTES);
   }
-
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestSubscriptionsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestSubscriptionsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestSubscriptionsDUnitTest.java
index 7d96517..52c7b9c 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestSubscriptionsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/pulse/TestSubscriptionsDUnitTest.java
@@ -15,6 +15,9 @@
 package org.apache.geode.management.internal.pulse;
 
 import static org.apache.geode.distributed.ConfigurationProperties.*;
+import static org.apache.geode.test.dunit.Host.*;
+import static org.apache.geode.test.dunit.NetworkUtils.*;
+import static org.apache.geode.test.dunit.Wait.*;
 import static org.junit.Assert.*;
 
 import java.util.Properties;
@@ -32,268 +35,173 @@ import org.apache.geode.cache.Scope;
 import org.apache.geode.cache.client.PoolManager;
 import org.apache.geode.cache.client.internal.PoolImpl;
 import org.apache.geode.cache.server.CacheServer;
-import org.apache.geode.distributed.DistributedMember;
 import org.apache.geode.distributed.DistributedSystem;
-import org.apache.geode.internal.AvailablePort;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
 import org.apache.geode.management.DistributedSystemMXBean;
 import org.apache.geode.management.ManagementService;
 import org.apache.geode.management.ManagementTestBase;
-import org.apache.geode.test.dunit.Assert;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.LogWriterUtils;
-import org.apache.geode.test.dunit.NetworkUtils;
-import org.apache.geode.test.dunit.SerializableCallable;
-import org.apache.geode.test.dunit.SerializableRunnable;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
 import org.apache.geode.test.dunit.WaitCriterion;
-import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
 import org.apache.geode.test.junit.categories.DistributedTest;
 
 /**
  * This is for testing subscriptions
  */
 @Category(DistributedTest.class)
-public class TestSubscriptionsDUnitTest extends JUnit4DistributedTestCase {
+@SuppressWarnings("serial")
+public class TestSubscriptionsDUnitTest extends ManagementTestBase {
 
-  private static final String k1 = "k1";
-  private static final String k2 = "k2";
-  private static final String client_k1 = "client-k1";
-
-  private static final String client_k2 = "client-k2";
   private static final String REGION_NAME =
       TestSubscriptionsDUnitTest.class.getSimpleName() + "_Region";
+
+  private static final String KEY1 = "k1";
+  private static final String KEY2 = "k2";
+  private static final String CLIENT_VALUE1 = "client-k1";
+  private static final String CLIENT_VALUE2 = "client-k2";
+
   private static VM server = null;
   private static VM client = null;
   private static VM client2 = null;
-  private static VM managingNode = null;
-  private ManagementTestBase helper;
-
-  @Override
-  public final void preSetUp() throws Exception {
-    this.helper = new ManagementTestBase() {};
-  }
 
   @Override
-  public final void postSetUp() throws Exception {
-    final Host host = Host.getHost(0);
-    managingNode = host.getVM(0);
-    server = host.getVM(1);
-    client = host.getVM(2);
-    client2 = host.getVM(3);
-  }
-
-  @Override
-  public final void preTearDown() throws Exception {
-    helper.closeCache(managingNode);
-    helper.closeCache(server);
-    helper.closeCache(client);
-    helper.closeCache(client2);
-    disconnectFromDS();
+  public final void postSetUpManagementTestBase() throws Exception {
+    server = getHost(0).getVM(1);
+    client = getHost(0).getVM(2);
+    client2 = getHost(0).getVM(3);
   }
 
   @Test
-  public void testNoOfSubscription() throws Exception {
+  public void testNumSubscriptions() throws Exception {
+    createManagementCache(managingNode);
+    startManagingNode(managingNode);
+
+    int port = createServerCache(server);
+    getMember(server);
 
-    helper.createManagementCache(managingNode);
-    helper.startManagingNode(managingNode);
+    createClientCache(client, getServerHostName(server.getHost()), port);
+    createClientCache(client2, getServerHostName(server.getHost()), port);
 
-    int port = (Integer) createServerCache(server);
-    DistributedMember serverMember = helper.getMember(server);
-    createClientCache(client, NetworkUtils.getServerHostName(server.getHost()), port);
-    createClientCache(client2, NetworkUtils.getServerHostName(server.getHost()), port);
     put(client);
     put(client2);
+
     registerInterest(client);
     registerInterest(client2);
-    verifyClientStats(managingNode, serverMember, port);
-    helper.stopManagingNode(managingNode);
-  }
 
-  @SuppressWarnings("serial")
-  private Object createServerCache(VM vm) {
-    return vm.invoke(new SerializableCallable("Create Server Cache in TestSubscriptionsDUnitTest") {
+    verifyNumSubscriptions(managingNode);
 
-      public Object call() {
-        try {
-          return createServerCache();
-        } catch (Exception e) {
-          fail("Error while createServerCache in TestSubscriptionsDUnitTest" + e);
-        }
-        return null;
-      }
-    });
+    stopManagingNode(managingNode);
   }
 
-  @SuppressWarnings("serial")
-  private void createClientCache(VM vm, final String host, final Integer port1) {
-    vm.invoke(new SerializableCallable("Create Client Cache in TestSubscriptionsDUnitTest") {
+  private int createServerCache(VM vm) {
+    return vm.invoke("Create Server Cache in TestSubscriptionsDUnitTest", () -> {
+      return createServerCache();
+    });
+  }
 
-      public Object call() {
-        try {
-          createClientCache(host, port1);
-        } catch (Exception e) {
-          fail("Error while createClientCache in TestSubscriptionsDUnitTest " + e);
-        }
-        return null;
-      }
+  private void createClientCache(VM vm, final String host, final int port1) {
+    vm.invoke("Create Client Cache in TestSubscriptionsDUnitTest", () -> {
+      createClientCache(host, port1);
     });
   }
 
   private Cache createCache(Properties props) throws Exception {
     DistributedSystem ds = getSystem(props);
-    ds.disconnect();
-    ds = getSystem(props);
-    assertNotNull(ds);
-    Cache cache = (GemFireCacheImpl) CacheFactory.create(ds);
-    assertNotNull(cache);
+    Cache cache = CacheFactory.create(ds);
     return cache;
   }
 
-  private Integer createServerCache(DataPolicy dataPolicy) throws Exception {
-    Cache cache = helper.createCache(false);
+  private int createServerCache(DataPolicy dataPolicy) throws Exception {
+    Cache cache = createCache(false);
+
     AttributesFactory factory = new AttributesFactory();
     factory.setScope(Scope.DISTRIBUTED_ACK);
     factory.setDataPolicy(dataPolicy);
-    RegionAttributes attrs = factory.create();
-    cache.createRegion(REGION_NAME, attrs);
-    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+
+    cache.createRegion(REGION_NAME, factory.create());
+
     CacheServer server1 = cache.addCacheServer();
-    server1.setPort(port);
+    server1.setPort(0);
     server1.setNotifyBySubscription(true);
     server1.start();
-    return new Integer(server1.getPort());
+
+    return server1.getPort();
   }
 
-  public Integer createServerCache() throws Exception {
+  private int createServerCache() throws Exception {
     return createServerCache(DataPolicy.REPLICATE);
   }
 
-  public Cache createClientCache(String host, Integer port1) throws Exception {
-
+  private Cache createClientCache(String host, int port1) throws Exception {
     Properties props = new Properties();
     props.setProperty(MCAST_PORT, "0");
     props.setProperty(LOCATORS, "");
+
     Cache cache = createCache(props);
-    PoolImpl p = (PoolImpl) PoolManager.createFactory().addServer(host, port1.intValue())
-        .setSubscriptionEnabled(true).setThreadLocalConnections(true).setMinConnections(1)
-        .setReadTimeout(20000).setPingInterval(10000).setRetryAttempts(1)
-        .setSubscriptionEnabled(true).setStatisticInterval(1000)
-        .create("TestSubscriptionsDUnitTest");
+
+    PoolImpl p =
+        (PoolImpl) PoolManager.createFactory().addServer(host, port1).setSubscriptionEnabled(true)
+            .setThreadLocalConnections(true).setMinConnections(1).setReadTimeout(20000)
+            .setPingInterval(10000).setRetryAttempts(1).setSubscriptionEnabled(true)
+            .setStatisticInterval(1000).create("TestSubscriptionsDUnitTest");
 
     AttributesFactory factory = new AttributesFactory();
     factory.setScope(Scope.DISTRIBUTED_ACK);
     factory.setPoolName(p.getName());
 
     RegionAttributes attrs = factory.create();
-    Region region = cache.createRegion(REGION_NAME, attrs);
-    return cache;
+    cache.createRegion(REGION_NAME, attrs);
 
+    return cache;
   }
 
-  /**
-   * get member id
-   */
-  @SuppressWarnings("serial")
-  protected static DistributedMember getMember() throws Exception {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    return cache.getDistributedSystem().getDistributedMember();
-  }
+  private void verifyNumSubscriptions(final VM vm) {
+    vm.invoke("TestSubscriptionsDUnitTest Verify Cache Server Remote", () -> {
+      final GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+
+      waitForCriterion(new WaitCriterion() {
+        @Override
+        public boolean done() {
+          ManagementService service = ManagementService.getExistingManagementService(cache);
+          DistributedSystemMXBean distributedSystemMXBean = service.getDistributedSystemMXBean();
+          return distributedSystemMXBean != null
+              & distributedSystemMXBean.getNumSubscriptions() > 1;
+        }
 
-  /**
-   * Verify the Cache Server details
-   * 
-   * @param vm
-   */
-  @SuppressWarnings("serial")
-  protected void verifyClientStats(final VM vm, final DistributedMember serverMember,
-      final int serverPort) {
-    SerializableRunnable verifyCacheServerRemote =
-        new SerializableRunnable("TestSubscriptionsDUnitTest Verify Cache Server Remote") {
-          public void run() {
-            final GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-            try {
-              final WaitCriterion waitCriteria = new WaitCriterion() {
-                @Override
-                public boolean done() {
-                  ManagementService service = ManagementService.getExistingManagementService(cache);
-                  final DistributedSystemMXBean dsBean = service.getDistributedSystemMXBean();
-                  if (dsBean != null) {
-                    if (dsBean.getNumSubscriptions() > 1) {
-                      return true;
-                    }
-                  }
-                  return false;
-                }
-
-                @Override
-                public String description() {
-                  return "TestSubscriptionsDUnitTest wait for getDistributedSystemMXBean to complete and get results";
-                }
-              };
-              Wait.waitForCriterion(waitCriteria, 2 * 60 * 1000, 3000, true);
-              final DistributedSystemMXBean dsBean = ManagementService
-                  .getExistingManagementService(cache).getDistributedSystemMXBean();
-              assertNotNull(dsBean);
-              LogWriterUtils.getLogWriter()
-                  .info("TestSubscriptionsDUnitTest dsBean.getNumSubscriptions() ="
-                      + dsBean.getNumSubscriptions());
-              assertTrue(dsBean.getNumSubscriptions() == 2 ? true : false);
-            } catch (Exception e) {
-              fail("TestSubscriptionsDUnitTest Error while verifying subscription "
-                  + e.getMessage());
-            }
-
-          }
-        };
-    vm.invoke(verifyCacheServerRemote);
-  }
+        @Override
+        public String description() {
+          return "TestSubscriptionsDUnitTest wait for getDistributedSystemMXBean to complete and get results";
+        }
+      }, 2 * 60 * 1000, 3000, true);
 
-  /**
-   * Verify the Cache Server details
-   * 
-   * @param vm
-   */
-  @SuppressWarnings("serial")
-  protected void registerInterest(final VM vm) {
-    SerializableRunnable put =
-        new SerializableRunnable("TestSubscriptionsDUnitTest registerInterest") {
-          public void run() {
-            try {
-              Cache cache = GemFireCacheImpl.getInstance();
-              Region<Object, Object> r1 = cache.getRegion(Region.SEPARATOR + REGION_NAME);
-              assertNotNull(r1);
-              r1.registerInterest(k1);
-              r1.registerInterest(k2);
-            } catch (Exception ex) {
-              Assert.fail("TestSubscriptionsDUnitTest failed while register Interest", ex);
-            }
-          }
-
-        };
-    vm.invoke(put);
+      DistributedSystemMXBean distributedSystemMXBean =
+          ManagementService.getExistingManagementService(cache).getDistributedSystemMXBean();
+      assertNotNull(distributedSystemMXBean);
+      assertEquals(2, distributedSystemMXBean.getNumSubscriptions());
+    });
   }
 
-  @SuppressWarnings("serial")
-  protected void put(final VM vm) {
-    SerializableRunnable put = new SerializableRunnable("put") {
-      public void run() {
-        try {
-          Cache cache = GemFireCacheImpl.getInstance();
-          Region r1 = cache.getRegion(Region.SEPARATOR + REGION_NAME);
-          assertNotNull(r1);
-          r1.put(k1, client_k1);
-          assertEquals(r1.getEntry(k1).getValue(), client_k1);
-          r1.put(k2, client_k2);
-          assertEquals(r1.getEntry(k2).getValue(), client_k2);
-        } catch (Exception ex) {
-          Assert.fail("failed while put", ex);
-        }
-      }
+  private void registerInterest(final VM vm) {
+    vm.invoke("TestSubscriptionsDUnitTest registerInterest", () -> {
+      Cache cache = GemFireCacheImpl.getInstance();
+      Region<Object, Object> region = cache.getRegion(Region.SEPARATOR + REGION_NAME);
+      assertNotNull(region);
 
-    };
-    vm.invoke(put);
+      region.registerInterest(KEY1);
+      region.registerInterest(KEY2);
+    });
   }
 
+  private void put(final VM vm) {
+    vm.invoke("put", () -> {
+      Cache cache = GemFireCacheImpl.getInstance();
+      Region region = cache.getRegion(Region.SEPARATOR + REGION_NAME);
+      assertNotNull(region);
+
+      region.put(KEY1, CLIENT_VALUE1);
+      assertEquals(CLIENT_VALUE1, region.getEntry(KEY1).getValue());
+
+      region.put(KEY2, CLIENT_VALUE2);
+      assertEquals(CLIENT_VALUE2, region.getEntry(KEY2).getValue());
+    });
+  }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/AsyncInvocation.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/AsyncInvocation.java b/geode-core/src/test/java/org/apache/geode/test/dunit/AsyncInvocation.java
index 460b562..057454d 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/AsyncInvocation.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/AsyncInvocation.java
@@ -316,6 +316,58 @@ public class AsyncInvocation<V> implements Future<V> {
   }
 
   /**
+   * Waits if necessary for at most the given time for the computation to complete.
+   *
+   * @param timeout the maximum time to wait
+   * @param unit the time unit of the timeout argument
+   *
+   * @return this {@code AsyncInvocation}
+   *
+   * @throws AssertionError wrapping any {@code Exception} thrown by this {@code AsyncInvocation}.
+   *
+   * @throws CancellationException if the computation was cancelled
+   *
+   * @throws ExecutionException if the computation threw an exception
+   *
+   * @throws InterruptedException if the current thread is interrupted.
+   *
+   * @throws TimeoutException if the wait timed out
+   */
+  public AsyncInvocation<V> await(final long timeout, final TimeUnit unit)
+      throws ExecutionException, InterruptedException, TimeoutException {
+    long millis = unit.toMillis(timeout);
+    join(millis);
+    timeoutIfAlive(millis);
+    checkException();
+    return this;
+  }
+
+  /**
+   * Waits if necessary for at most the given time for the computation to complete.
+   *
+   * @return this {@code AsyncInvocation}
+   *
+   * @throws AssertionError wrapping any {@code Exception} thrown by this {@code AsyncInvocation}.
+   *
+   * @throws AssertionError wrapping a {@code TimeoutException} if this {@code AsyncInvocation}
+   *         fails to complete within the default timeout of 60 seconds as defined by
+   *         {@link #DEFAULT_JOIN_MILLIS}.
+   *
+   * @throws CancellationException if the computation was cancelled
+   *
+   * @throws ExecutionException if the computation threw an exception
+   *
+   * @throws InterruptedException if the current thread is interrupted.
+   */
+  public AsyncInvocation<V> await() throws ExecutionException, InterruptedException {
+    try {
+      return await(DEFAULT_JOIN_MILLIS, TimeUnit.MILLISECONDS);
+    } catch (TimeoutException timeoutException) {
+      throw new AssertionError(timeoutException);
+    }
+  }
+
+  /**
    * Waits if necessary for the work to complete, and then returns the result of this
    * {@code AsyncInvocation}.
    *
@@ -353,10 +405,6 @@ public class AsyncInvocation<V> implements Future<V> {
    *
    * @throws AssertionError wrapping any {@code Exception} thrown by this {@code AsyncInvocation}.
    *
-   * @throws AssertionError wrapping a {@code TimeoutException} if this {@code AsyncInvocation}
-   *         fails to complete within the default timeout of 60 seconds as defined by
-   *         {@link #DEFAULT_JOIN_MILLIS}.
-   *
    * @throws CancellationException if the computation was cancelled
    *
    * @throws ExecutionException if the computation threw an exception

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/Invoke.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/Invoke.java b/geode-core/src/test/java/org/apache/geode/test/dunit/Invoke.java
index a09f5ff..af7e217 100755
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/Invoke.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/Invoke.java
@@ -22,13 +22,13 @@ import java.util.Map;
  * invoke a <code>SerializableRunnable</code> or <code>SerializableCallable</code> in a remote test
  * <code>VM</code>.
  * 
- * These methods can be used directly: <code>Invoke.invokeInEveryVM(...)</code>, however, they are
- * intended to be referenced through static import:
+ * These methods can be used directly: <code>Invoke.invokeInEveryVMAndController(...)</code>,
+ * however, they are intended to be referenced through static import:
  *
  * <pre>
  * import static org.apache.geode.test.dunit.Invoke.*;
  *    ...
- *    invokeInEveryVM(...);
+ *    invokeInEveryVMAndController(...);
  * </pre>
  *
  * Extracted from DistributedTestCase.

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/VM.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/VM.java b/geode-core/src/test/java/org/apache/geode/test/dunit/VM.java
index 04d2951..9a42caa 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/VM.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/VM.java
@@ -24,6 +24,7 @@ import java.util.concurrent.Callable;
 import com.jayway.awaitility.Awaitility;
 import hydra.MethExecutorResult;
 
+import org.apache.geode.internal.process.PidUnavailableException;
 import org.apache.geode.internal.process.ProcessUtils;
 import org.apache.geode.test.dunit.standalone.BounceResult;
 import org.apache.geode.test.dunit.standalone.RemoteDUnitVMIF;
@@ -91,7 +92,11 @@ public class VM implements Serializable {
    * Returns the process id of this {@code VM}.
    */
   public int getPid() {
-    return this.pid;
+    // try {
+    return invoke(() -> ProcessUtils.identifyPid());
+    // } catch (PidUnavailableException e) {
+    // return this.pid;
+    // }
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/Wait.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/Wait.java b/geode-core/src/test/java/org/apache/geode/test/dunit/Wait.java
index f25810e..7d4e6d5 100755
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/Wait.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/Wait.java
@@ -17,6 +17,8 @@ package org.apache.geode.test.dunit;
 import static org.apache.geode.test.dunit.Jitter.*;
 import static org.junit.Assert.*;
 
+import java.io.Serializable;
+
 import org.apache.logging.log4j.Logger;
 
 import org.apache.geode.internal.cache.LocalRegion;

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java b/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java
index 037d73c..a511995 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/cache/internal/JUnit4CacheTestCase.java
@@ -245,6 +245,11 @@ public abstract class JUnit4CacheTestCase extends JUnit4DistributedTestCase
     return getCache(false, factory);
   }
 
+  public final Cache getCache(final Properties properties) {
+    getSystem(properties);
+    return getCache();
+  }
+
   public final Cache getCache(final boolean client) {
     return getCache(client, null);
   }

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java b/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java
index c54b6ac..19949c2 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/internal/JUnit4DistributedTestCase.java
@@ -113,7 +113,7 @@ public abstract class JUnit4DistributedTestCase implements DistributedTestFixtur
   }
 
   @Rule
-  public SerializableTestName testName = new SerializableTestName();
+  public SerializableTestName testNameForDistributedTestCase = new SerializableTestName();
 
   private static DUnitBlackboard blackboard;
 
@@ -139,7 +139,7 @@ public abstract class JUnit4DistributedTestCase implements DistributedTestFixtur
     if (this.distributedTestFixture != this) {
       return this.distributedTestFixture.getName();
     }
-    return this.testName.getMethodName();
+    return this.testNameForDistributedTestCase.getMethodName();
   }
 
   public final Class<? extends DistributedTestFixture> getTestClass() {

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDisconnectRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDisconnectRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDisconnectRule.java
index ddf37c5..9107d4d 100755
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDisconnectRule.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedDisconnectRule.java
@@ -43,14 +43,14 @@ public class DistributedDisconnectRule extends DistributedExternalResource {
   @Override
   protected void before() throws Throwable {
     if (this.disconnectBefore) {
-      invoker().invokeEverywhere(serializableRunnable());
+      invoker().invokeInEveryVMAndController(serializableRunnable());
     }
   }
 
   @Override
   protected void after() {
     if (this.disconnectAfter) {
-      invoker().invokeEverywhere(serializableRunnable());
+      invoker().invokeInEveryVMAndController(serializableRunnable());
     }
   }
 

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRestoreSystemProperties.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRestoreSystemProperties.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRestoreSystemProperties.java
index 6b9102e..21c2f45 100755
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRestoreSystemProperties.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRestoreSystemProperties.java
@@ -46,7 +46,7 @@ public class DistributedRestoreSystemProperties extends RestoreSystemProperties
   @Override
   public void before() throws Throwable {
     super.before();
-    this.invoker.remoteInvokeInEveryVMAndLocator(new SerializableRunnable() {
+    this.invoker.invokeInEveryVMAndController(new SerializableRunnable() {
       @Override
       public void run() {
         originalProperties = getProperties();
@@ -58,7 +58,7 @@ public class DistributedRestoreSystemProperties extends RestoreSystemProperties
   @Override
   public void after() {
     super.after();
-    this.invoker.remoteInvokeInEveryVMAndLocator(new SerializableRunnable() {
+    this.invoker.invokeInEveryVMAndController(new SerializableRunnable() {
       @Override
       public void run() {
         setProperties(originalProperties);

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRule.java
new file mode 100644
index 0000000..8e89bdb
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRule.java
@@ -0,0 +1,66 @@
+/*
+ * 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.geode.test.dunit.rules;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import org.junit.Rule;
+
+/**
+ * Annotates a field or method as a type of {@link Rule} that can be invoked across multiple VMs in
+ * a {@code DistributedTest}.
+ *
+ * If there are multiple annotated {@code DistributedRule}s on a class, they will be applied in
+ * order of fields first, then methods. Furthermore, if there are multiple fields (or methods) they
+ * will be applied in an order that depends on your JVM's implementation of the reflection API,
+ * which is undefined. Rules defined by fields will always be applied before Rules defined by
+ * methods. You can use a {@link org.junit.rules.RuleChain} or
+ * {@link org.apache.geode.test.junit.rules.RuleList} if you want to have control over the order in
+ * which the Rules are applied.
+ *
+ * <p>
+ * For example, here is a test class that makes a unique {@link org.junit.rules.TemporaryFolder}
+ * available to each DUnit VM:
+ * 
+ * <pre>
+ * {@literal @}Category(DistributedTest.class)
+ * public class EachVMHasItsOwnTemporaryFolder {
+ *
+ *   {@literal @}DistributedRule
+ *   public TemporaryFolder folder = new TemporaryFolder();
+ *
+ *   {@literal @}Rule
+ *   public DistributedTestRule distributedTestRule = DistributedTestRule.builder().build();
+ *
+ *   {@literal @}Test
+ *   public void eachVMHasItsOwnTemporaryFolder() throws Exception {
+ *     Host.getHost(0).getVM(0).invoke(() -> {
+ *       File gemfireProps = folder.newFile({@literal "}gemfire.properties{@literal "});
+ *       File diskDirs = folder.newFolder({@literal "}diskDirs{@literal "});
+ *       ...
+ *     }
+ *   }
+ * }
+ * </pre>
+ *
+ * @see org.apache.geode.test.junit.rules.serializable.SerializableTestRule
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.FIELD, ElementType.METHOD})
+public @interface DistributedRule {
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRunRules.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRunRules.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRunRules.java
new file mode 100644
index 0000000..7a86613
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedRunRules.java
@@ -0,0 +1,76 @@
+/*
+ * 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.geode.test.dunit.rules;
+
+import java.io.Serializable;
+
+import org.junit.rules.TestRule;
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
+
+import org.apache.geode.test.dunit.Host;
+import org.apache.geode.test.dunit.SerializableRunnable;
+
+/**
+ * Runs Rules in specified DUnit VMs.
+ */
+public class DistributedRunRules extends Statement implements Serializable {
+  private final Statement statement;
+  private final WhichVMs whichVMs;
+
+  public DistributedRunRules(final Statement base, final Iterable<TestRule> rules,
+      final Description description, final WhichVMs whichVMs) {
+    this.statement = applyAll(base, rules, description);
+    this.whichVMs = whichVMs;
+  }
+
+  @Override
+  public void evaluate() throws Throwable {
+    if (this.whichVMs.controllerVM()) {
+      this.statement.evaluate();
+    }
+    if (this.whichVMs.everyVM()) {
+      for (int i = 0; i < Host.getHost(0).getVMCount(); i++) {
+        Host.getHost(0).getVM(i).invoke(runnable());
+      }
+    }
+    if (this.whichVMs.locatorVM()) {
+      Host.getHost(0).getLocator().invoke(runnable());
+    }
+  }
+
+  private Statement applyAll(Statement result, final Iterable<TestRule> rules,
+      final Description description) {
+    for (TestRule each : rules) {
+      result = each.apply(result, description);
+    }
+    return result;
+  }
+
+  private SerializableRunnable runnable() {
+    return new SerializableRunnable() {
+      @Override
+      public void run() {
+        try {
+          DistributedRunRules.this.statement.evaluate();
+        } catch (Error | RuntimeException e) {
+          throw e;
+        } catch (Throwable t) {
+          throw new RuntimeException(t);
+        }
+      }
+    };
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedStatement.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedStatement.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedStatement.java
new file mode 100644
index 0000000..cdc8dda
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedStatement.java
@@ -0,0 +1,75 @@
+/*
+ * 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.geode.test.dunit.rules;
+
+import java.io.Serializable;
+
+import org.junit.runners.model.Statement;
+
+import org.apache.geode.test.dunit.Host;
+import org.apache.geode.test.dunit.SerializableRunnable;
+import org.apache.geode.test.junit.rules.serializable.SerializableStatement;
+
+/**
+ * Invokes Statement in specified DUnit VMs.
+ */
+public class DistributedStatement extends SerializableStatement {
+  private final SerializableStatement next;
+  private final WhichVMs whichVMs;
+
+  /**
+   * Construct a new {@code DistributedStatement} statement.
+   * 
+   * @param next the next {@code Statement} in the execution chain
+   * @param whichVMs specifies which VMs should invoke the statement
+   */
+  public DistributedStatement(final SerializableStatement next, final WhichVMs whichVMs) {
+    this.next = next;
+    this.whichVMs = whichVMs;
+  }
+
+  /**
+   * Invoke the {@link Statement} in the specified VMs.
+   */
+  @Override
+  public void evaluate() throws Throwable {
+    if (this.whichVMs.controllerVM()) {
+      this.next.evaluate();
+    }
+    if (this.whichVMs.everyVM()) {
+      for (int i = 0; i < Host.getHost(0).getVMCount(); i++) {
+        Host.getHost(0).getVM(i).invoke(runnable());
+      }
+    }
+    if (this.whichVMs.locatorVM()) {
+      Host.getHost(0).getLocator().invoke(runnable());
+    }
+  }
+
+  private SerializableRunnable runnable() {
+    return new SerializableRunnable() {
+      @Override
+      public void run() {
+        try {
+          next.evaluate();
+        } catch (Error | RuntimeException e) {
+          throw e;
+        } catch (Throwable t) {
+          throw new RuntimeException(t);
+        }
+      }
+    };
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedTestRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedTestRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedTestRule.java
new file mode 100644
index 0000000..31fba3d
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedTestRule.java
@@ -0,0 +1,200 @@
+/*
+ * 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.geode.test.dunit.rules;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.rules.MethodRule;
+import org.junit.rules.TestRule;
+import org.junit.runner.Description;
+import org.junit.runners.model.FrameworkMethod;
+import org.junit.runners.model.Statement;
+import org.junit.runners.model.TestClass;
+
+import org.apache.geode.test.dunit.standalone.DUnitLauncher;
+
+/**
+ * Launches the DUnit framework for a {@code DistributedTest}.
+ *
+ * <p>
+ * Enables use of {@link DistributedRule} annotations on any Rules.
+ *
+ * <pre>
+ * {@literal @}Category(DistributedTest.class)
+ * public class QueryDataDUnitTest {
+ *
+ *   {@literal @}DistributedRule
+ *   public UseJacksonForJsonPathRule useJacksonForJsonPathRule = new UseJacksonForJsonPathRule();
+ *
+ *   {@literal @}Rule
+ *   public DistributedTestRule distributedTestRule = DistributedTestRule.builder().build();
+ *
+ *   ...
+ * }
+ * </pre>
+ * <p>
+ * Use the {@code Builder} to specify which {@code VM}s should invoke any {@code Rule} annotated
+ * with {@literal @}DistributedRule. By default, {@code controllerVM} is {@code true},
+ * {@code everyVM} is {@code true} and {@code locatorVM} is {@code false}.
+ */
+public class DistributedTestRule implements MethodRule, Serializable {
+
+  public static Builder builder() {
+    return new Builder();
+  }
+
+  private TestClass testClass;
+
+  private final List<?> rules = new ArrayList<>(); // types are TestRule or MethodRule
+
+  private final RemoteInvoker invoker;
+
+  private final WhichVMs whichVMs;
+
+  // TODO: add ability to specify ordering of DistributedRules
+
+  protected DistributedTestRule(final Builder builder) {
+    this(new RemoteInvoker(), builder);
+  }
+
+  protected DistributedTestRule(final RemoteInvoker invoker, final Builder builder) {
+    this.invoker = invoker;
+
+    this.whichVMs = new WhichVMs();
+    if (builder.controllerVM) {
+      this.whichVMs.addControllerVM();
+    }
+    if (builder.everyVM) {
+      this.whichVMs.addEveryVM();
+    }
+    if (builder.locatorVM) {
+      this.whichVMs.addLocatorVM();
+    }
+  }
+
+  @Override
+  public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
+    this.testClass = new TestClass(target.getClass());
+    Statement statement = base;
+    statement = withRules(method, target, statement);
+    statement = withDUnit(method, target, statement);
+    return statement;
+  }
+
+  protected Statement withDUnit(final FrameworkMethod method, final Object target,
+      final Statement statement) {
+    return new Statement() {
+      @Override
+      public void evaluate() throws Throwable {
+        setUpDUnit();
+        try {
+          statement.evaluate();
+        } finally {
+          tearDownDUnit();
+        }
+      }
+    };
+  }
+
+  protected void setUpDUnit() throws Exception {
+    DUnitLauncher.launchIfNeeded();
+    // TODO: customize based on fields
+  }
+
+  protected void tearDownDUnit() throws Exception {}
+
+  protected Statement withRules(final FrameworkMethod method, final Object target,
+      final Statement statement) {
+    List<TestRule> testRules = this.testRules(target);
+    Statement result = statement;
+    // result = withMethodRules(method, testRules, target, result);
+    result = withTestRules(method, testRules, result);
+
+    return result;
+  }
+
+  // protected Statement withMethodRules(final FrameworkMethod method, final List<TestRule>
+  // testRules, final Object target, final Statement result) {
+  // Statement statement = result;
+  // for (MethodRule rule : methodRules(target)) {
+  // if (!testRules.contains(rule)) {
+  // statement = new DistributedStatement(rule.apply((result, method, target), this.whichVMs);
+  // }
+  // }
+  // return statement;
+  // }
+
+  protected Statement withTestRules(final FrameworkMethod method, final List<TestRule> testRules,
+      final Statement statement) {
+    Description description = Description.createTestDescription(this.testClass.getJavaClass(),
+        method.getName(), method.getAnnotations());
+    return testRules.isEmpty() ? statement
+        : new DistributedRunRules(statement, testRules, description, this.whichVMs);
+  }
+
+  protected List<MethodRule> methodRules(final Object target) {
+    List<MethodRule> rules =
+        this.testClass.getAnnotatedMethodValues(target, DistributedRule.class, MethodRule.class);
+    rules.addAll(
+        this.testClass.getAnnotatedFieldValues(target, DistributedRule.class, MethodRule.class));
+    return rules;
+  }
+
+  protected List<TestRule> testRules(final Object target) {
+    List<TestRule> result =
+        this.testClass.getAnnotatedMethodValues(target, DistributedRule.class, TestRule.class);
+    result.addAll(
+        this.testClass.getAnnotatedFieldValues(target, DistributedRule.class, TestRule.class));
+    return result;
+  }
+
+  /**
+   * Builds an instance of {@link DistributedTestRule}.
+   *
+   * <p>
+   * By default, {@code controllerVM} is {@code true}, {@code everyVM} is {@code true} and
+   * {@code locatorVM} is {@code false}.
+   */
+  public static class Builder {
+
+    private boolean everyVM = true;
+    private boolean locatorVM = false;
+    private boolean controllerVM = true;
+
+    protected Builder() {}
+
+    public Builder everyVM(final boolean everyVM) {
+      this.everyVM = everyVM;
+      return this;
+    }
+
+    public Builder locatorVM(final boolean locatorVM) {
+      this.locatorVM = locatorVM;
+      return this;
+    }
+
+    public Builder controllerVM(final boolean locatorVM) {
+      this.locatorVM = locatorVM;
+      return this;
+    }
+
+    public DistributedTestRule build() {
+      return new DistributedTestRule(this);
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedUseJacksonForJsonPathRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedUseJacksonForJsonPathRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedUseJacksonForJsonPathRule.java
new file mode 100644
index 0000000..8c85775
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedUseJacksonForJsonPathRule.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package org.apache.geode.test.dunit.rules;
+
+import org.apache.geode.test.junit.rules.UseJacksonForJsonPathRule;
+
+public class DistributedUseJacksonForJsonPathRule extends UseJacksonForJsonPathRule {
+
+  private static UseJacksonForJsonPathRule instance = new UseJacksonForJsonPathRule();
+
+  private final RemoteInvoker invoker;
+
+  public DistributedUseJacksonForJsonPathRule() {
+    this(new RemoteInvoker());
+  }
+
+  public DistributedUseJacksonForJsonPathRule(final RemoteInvoker invoker) {
+    this.invoker = invoker;
+  }
+
+  @Override
+  public void before() {
+    this.invoker.invokeInEveryVMAndController(DistributedUseJacksonForJsonPathRule::invokeBefore);
+  }
+
+  @Override
+  public void after() {
+    this.invoker.invokeInEveryVMAndController(DistributedUseJacksonForJsonPathRule::invokeAfter);
+  }
+
+  private static void invokeBefore() {
+    instance.before();
+  }
+
+  private static void invokeAfter() {
+    instance.after();
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedWrapperRule.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedWrapperRule.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedWrapperRule.java
new file mode 100644
index 0000000..6b1f8f1
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/DistributedWrapperRule.java
@@ -0,0 +1,51 @@
+/*
+ * 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.geode.test.dunit.rules;
+
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
+
+import org.apache.geode.test.junit.rules.UseJacksonForJsonPathRule;
+import org.apache.geode.test.junit.rules.serializable.SerializableExternalResource;
+import org.apache.geode.test.junit.rules.serializable.SerializableStatement;
+import org.apache.geode.test.junit.rules.serializable.SerializableTestRule;
+
+public class DistributedWrapperRule implements SerializableTestRule {
+
+  private static SerializableTestRule instance;
+
+  private final RemoteInvoker invoker;
+  private final WhichVMs whichVMs;
+
+  public DistributedWrapperRule(final SerializableTestRule testRule) {
+    this(testRule, new WhichVMs().addControllerVM().addEveryVM());
+  }
+
+  public DistributedWrapperRule(final SerializableTestRule testRule, final WhichVMs whichVMs) {
+    this(new RemoteInvoker(), testRule, whichVMs);
+  }
+
+  public DistributedWrapperRule(final RemoteInvoker invoker, final SerializableTestRule testRule,
+      final WhichVMs whichVMs) {
+    this.invoker = invoker;
+    instance = testRule;
+    this.whichVMs = whichVMs;
+  }
+
+  @Override
+  public Statement apply(Statement base, Description description) {
+    return new DistributedStatement((SerializableStatement) base, whichVMs);
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/rules/RemoteInvoker.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/RemoteInvoker.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/RemoteInvoker.java
index 6398e45..866a0d5 100755
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/RemoteInvoker.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/RemoteInvoker.java
@@ -18,7 +18,8 @@ import static org.apache.geode.test.dunit.Invoke.*;
 
 import java.io.Serializable;
 
-import org.apache.geode.test.dunit.SerializableRunnable;
+import org.apache.geode.test.dunit.Invoke;
+import org.apache.geode.test.dunit.SerializableRunnableIF;
 
 /**
  * Provides remote invocation support to a {@code TestRule}. These methods will invoke a
@@ -28,18 +29,21 @@ class RemoteInvoker implements Serializable {
 
   private static final long serialVersionUID = -1759722991299584649L;
 
-  public void invokeEverywhere(final SerializableRunnable runnable) {
+  // controller VM
+  // dunit VMs
+  // locator VM
+
+  public void invokeInEveryVMAndController(final SerializableRunnableIF runnable) {
     try {
       runnable.run();
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
-    invokeInEveryVM(runnable);
-    invokeInLocator(runnable);
+    Invoke.invokeInEveryVM(runnable);
   }
 
-  public void remoteInvokeInEveryVMAndLocator(final SerializableRunnable runnable) {
-    invokeInEveryVM(runnable);
+  public void invokeInEveryVMAndLocator(final SerializableRunnableIF runnable) {
+    Invoke.invokeInEveryVM(runnable);
     invokeInLocator(runnable);
   }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/rules/WhichVMs.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/WhichVMs.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/WhichVMs.java
new file mode 100644
index 0000000..1048f2e
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/WhichVMs.java
@@ -0,0 +1,59 @@
+/*
+ * 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.geode.test.dunit.rules;
+
+import java.io.Serializable;
+
+/**
+ * Specifies which DUnit VMs will invoke a Rule.
+ *
+ * TODO: add ability to specify specific VMs
+ *
+ * TODO: add ability to specify order
+ */
+public class WhichVMs implements Serializable {
+  private boolean controllerVM;
+  private boolean everyVM;
+  private boolean locatorVM;
+
+  public WhichVMs() {}
+
+  public WhichVMs addControllerVM() {
+    this.controllerVM = true;
+    return this;
+  }
+
+  public WhichVMs addEveryVM() {
+    this.everyVM = true;
+    return this;
+  }
+
+  public WhichVMs addLocatorVM() {
+    this.locatorVM = true;
+    return this;
+  }
+
+  public boolean controllerVM() {
+    return this.controllerVM;
+  }
+
+  public boolean everyVM() {
+    return this.everyVM;
+  }
+
+  public boolean locatorVM() {
+    return this.locatorVM;
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedTestRuleTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedTestRuleTest.java b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedTestRuleTest.java
new file mode 100644
index 0000000..14ed14b
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/rules/tests/DistributedTestRuleTest.java
@@ -0,0 +1,53 @@
+/*
+ * 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.geode.test.dunit.rules.tests;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.test.dunit.rules.DistributedRule;
+import org.apache.geode.test.dunit.rules.DistributedTestRule;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.rules.serializable.SerializableExternalResource;
+
+// TODO: add assertions to all dunit VMs
+@Category(DistributedTest.class)
+public class DistributedTestRuleTest {
+
+  @DistributedRule
+  public SimpleRule simpleRule = new SimpleRule();
+
+  @Rule
+  public DistributedTestRule distributedTestRule = DistributedTestRule.builder().build();
+
+  @Test
+  public void test() throws Exception {
+    System.out.println("KIRK:test");
+  }
+
+  private static class SimpleRule extends SerializableExternalResource {
+    @Override
+    protected void before() throws Throwable {
+      System.out.println("KIRK:before");
+    }
+
+    @Override
+    protected void after() {
+      System.out.println("KIRK:after");
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/test/dunit/standalone/DUnitLauncher.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/test/dunit/standalone/DUnitLauncher.java b/geode-core/src/test/java/org/apache/geode/test/dunit/standalone/DUnitLauncher.java
index 8587ea5..d6f2013 100644
--- a/geode-core/src/test/java/org/apache/geode/test/dunit/standalone/DUnitLauncher.java
+++ b/geode-core/src/test/java/org/apache/geode/test/dunit/standalone/DUnitLauncher.java
@@ -36,21 +36,51 @@ import org.apache.logging.log4j.core.appender.FileAppender;
 import org.apache.logging.log4j.core.config.LoggerConfig;
 import org.apache.logging.log4j.core.layout.PatternLayout;
 import org.junit.Assert;
+import static org.apache.geode.distributed.ConfigurationProperties.*;
 
-import java.io.*;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.IOException;
 import java.lang.reflect.Method;
 import java.net.InetAddress;
 import java.net.URISyntaxException;
 import java.nio.channels.FileChannel;
 import java.nio.charset.Charset;
-import java.rmi.*;
+import java.rmi.AccessException;
+import java.rmi.AlreadyBoundException;
+import java.rmi.NotBoundException;
+import java.rmi.Remote;
+import java.rmi.RemoteException;
 import java.rmi.registry.LocateRegistry;
 import java.rmi.registry.Registry;
 import java.rmi.server.UnicastRemoteObject;
 import java.util.List;
 import java.util.Properties;
 
-import static org.apache.geode.distributed.ConfigurationProperties.*;
+import batterytest.greplogs.ExpectedStrings;
+import batterytest.greplogs.LogConsumer;
+import hydra.MethExecutorResult;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.core.appender.FileAppender;
+import org.apache.logging.log4j.core.config.LoggerConfig;
+import org.apache.logging.log4j.core.layout.PatternLayout;
+import org.junit.Assert;
+
+import org.apache.geode.distributed.Locator;
+import org.apache.geode.distributed.internal.DistributionConfig;
+import org.apache.geode.distributed.internal.InternalLocator;
+import org.apache.geode.distributed.internal.membership.gms.membership.GMSJoinLeave;
+import org.apache.geode.internal.AvailablePortHelper;
+import org.apache.geode.internal.logging.LogService;
+import org.apache.geode.test.dunit.DUnitEnv;
+import org.apache.geode.test.dunit.Host;
+import org.apache.geode.test.dunit.SerializableCallable;
+import org.apache.geode.test.dunit.VM;
 
 /**
  * A class to build a fake test configuration and launch some DUnit VMS.
@@ -75,6 +105,9 @@ public class DUnitLauncher {
   private static final int LOCATOR_VM_NUM = -2;
 
   static final long STARTUP_TIMEOUT = 120 * 1000;
+  private static final String STARTUP_TIMEOUT_MESSAGE =
+      "VMs did not start up within " + (STARTUP_TIMEOUT / 1000) + " seconds";
+
   private static final String SUSPECT_FILENAME = "dunit_suspect.log";
   private static File DUNIT_SUSPECT_FILE;
 
@@ -195,7 +228,7 @@ public class DUnitLauncher {
 
     // wait for the VM to start up
     if (!processManager.waitForVMs(STARTUP_TIMEOUT)) {
-      throw new RuntimeException("VMs did not start up with 30 seconds");
+      throw new RuntimeException("VMs did not start up within 30 seconds");
     }
 
     locatorPort = startLocator(registry);
@@ -210,7 +243,7 @@ public class DUnitLauncher {
 
     // wait for the VMS to start up
     if (!processManager.waitForVMs(STARTUP_TIMEOUT)) {
-      throw new RuntimeException("VMs did not start up with 30 seconds");
+      throw new RuntimeException("VMs did not start up within 30 seconds");
     }
 
     // populate the Host class with our stubs. The tests use this host class

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-junit/build.gradle
----------------------------------------------------------------------
diff --git a/geode-junit/build.gradle b/geode-junit/build.gradle
index f7e5e46..e47095f 100755
--- a/geode-junit/build.gradle
+++ b/geode-junit/build.gradle
@@ -16,6 +16,7 @@
  */
 
 dependencies {
+  compile 'com.jayway.jsonpath:json-path:' + project.'json-path.version'
   testCompile 'commons-lang:commons-lang:' + project.'commons-lang.version'
   testCompile 'com.google.guava:guava:' + project.'guava.version'
   testCompile 'org.assertj:assertj-core:' + project.'assertj-core.version'

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-junit/src/main/java/org/apache/geode/test/junit/rules/UseJacksonForJsonPathRule.java
----------------------------------------------------------------------
diff --git a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/UseJacksonForJsonPathRule.java b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/UseJacksonForJsonPathRule.java
new file mode 100644
index 0000000..c7c326a
--- /dev/null
+++ b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/UseJacksonForJsonPathRule.java
@@ -0,0 +1,128 @@
+/*
+ * 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.geode.test.junit.rules;
+
+import java.util.EnumSet;
+import java.util.Set;
+
+import com.jayway.jsonpath.Configuration;
+import com.jayway.jsonpath.Configuration.Defaults;
+import com.jayway.jsonpath.Option;
+import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
+import com.jayway.jsonpath.spi.json.JsonProvider;
+import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
+import com.jayway.jsonpath.spi.mapper.MappingProvider;
+
+import org.apache.geode.test.junit.rules.serializable.SerializableExternalResource;
+
+/**
+ * JUnit Rule that configures json-path to use the {@code JacksonJsonProvider}
+ *
+ * <p>
+ * UseJacksonForJsonPathRule can be used in tests that need to use json-path-assert:
+ * 
+ * <pre>
+ * {@literal @}ClassRule
+ * public static UseJacksonForJsonPathRule useJacksonForJsonPathRule = new UseJacksonForJsonPathRule();
+ *
+ * {@literal @}Test
+ * public void hasAssertionsUsingJsonPathMatchers() {
+ *   ...
+ *   assertThat(json, isJson());
+ *   assertThat(json, hasJsonPath("$.result"));
+ * }
+ * </pre>
+ */
+@SuppressWarnings({"serial", "unused"})
+public class UseJacksonForJsonPathRule extends SerializableExternalResource {
+
+  private boolean hadDefaults;
+  private JsonProvider jsonProvider;
+  private MappingProvider mappingProvider;
+  private Set<Option> options;
+
+  /**
+   * Override to set up your specific external resource.
+   */
+  @Override
+  public void before() {
+    saveDefaults();
+    Configuration.setDefaults(new Defaults() {
+
+      private final JsonProvider jsonProvider = new JacksonJsonProvider();
+      private final MappingProvider mappingProvider = new JacksonMappingProvider();
+
+      @Override
+      public JsonProvider jsonProvider() {
+        return jsonProvider;
+      }
+
+      @Override
+      public MappingProvider mappingProvider() {
+        return mappingProvider;
+      }
+
+      @Override
+      public Set<Option> options() {
+        return EnumSet.noneOf(Option.class);
+      }
+
+    });
+  }
+
+  /**
+   * Override to tear down your specific external resource.
+   */
+  @Override
+  public void after() {
+    restoreDefaults();
+  }
+
+  private void saveDefaults() {
+    try {
+      Configuration defaultConfiguration = Configuration.defaultConfiguration();
+      this.jsonProvider = defaultConfiguration.jsonProvider();
+      this.mappingProvider = defaultConfiguration.mappingProvider();
+      this.options = defaultConfiguration.getOptions();
+      this.hadDefaults = true;
+    } catch (NoClassDefFoundError ignore) {
+      this.hadDefaults = false;
+    }
+  }
+
+  private void restoreDefaults() {
+    if (!this.hadDefaults) {
+      return;
+    }
+    Configuration.setDefaults(new Defaults() {
+
+      @Override
+      public JsonProvider jsonProvider() {
+        return jsonProvider;
+      }
+
+      @Override
+      public MappingProvider mappingProvider() {
+        return mappingProvider;
+      }
+
+      @Override
+      public Set<Option> options() {
+        return options;
+      }
+
+    });
+  }
+}

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableExternalResource.java
----------------------------------------------------------------------
diff --git a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableExternalResource.java b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableExternalResource.java
index c76ed19..be561df 100755
--- a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableExternalResource.java
+++ b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableExternalResource.java
@@ -14,11 +14,33 @@
  */
 package org.apache.geode.test.junit.rules.serializable;
 
+import java.io.Serializable;
+
 import org.junit.rules.ExternalResource;
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
 
 /**
  * Serializable subclass of {@link org.junit.rules.ExternalResource ExternalResource}.
  */
 public abstract class SerializableExternalResource extends ExternalResource
     implements SerializableTestRule {
+
+  public Statement apply(Statement base, Description description) {
+    return statement(base);
+  }
+
+  private Statement statement(final Statement base) {
+    return new SerializableStatement() {
+      @Override
+      public void evaluate() throws Throwable {
+        before();
+        try {
+          base.evaluate();
+        } finally {
+          after();
+        }
+      }
+    };
+  }
 }

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableStatement.java
----------------------------------------------------------------------
diff --git a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableStatement.java b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableStatement.java
new file mode 100644
index 0000000..9251e83
--- /dev/null
+++ b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/serializable/SerializableStatement.java
@@ -0,0 +1,25 @@
+/*
+ * 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.geode.test.junit.rules.serializable;
+
+import java.io.Serializable;
+
+import org.junit.runners.model.Statement;
+
+/**
+ * Serializable subclass of {@link Statement}.
+ */
+public abstract class SerializableStatement extends Statement implements Serializable {
+}


[8/8] geode git commit: Convert from ManagementTestCase to ManagementTestRule

Posted by kl...@apache.org.
Convert from ManagementTestCase to ManagementTestRule


Project: http://git-wip-us.apache.org/repos/asf/geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/geode/commit/a409b5a2
Tree: http://git-wip-us.apache.org/repos/asf/geode/tree/a409b5a2
Diff: http://git-wip-us.apache.org/repos/asf/geode/diff/a409b5a2

Branch: refs/heads/feature/GEODE-1930-2
Commit: a409b5a2e0ade84d62ef26c4fff886541d7ecc20
Parents: 638b058
Author: Kirk Lund <kl...@apache.org>
Authored: Mon Oct 31 13:45:28 2016 -0700
Committer: Kirk Lund <kl...@apache.org>
Committed: Thu Jan 5 14:22:56 2017 -0800

----------------------------------------------------------------------
 .../RestAPIsAndInterOpsDUnitTest.java           |   46 +-
 geode-core/build.gradle                         |    1 +
 .../org/apache/geode/management/JVMMetrics.java |    3 +-
 .../org/apache/geode/management/OSMetrics.java  |    3 +-
 .../internal/SystemManagementService.java       |    3 +-
 .../DistributedLockServiceDUnitTest.java        |    2 +-
 .../cache/ConnectDisconnectDUnitTest.java       |    2 +-
 ...gionBucketCreationDistributionDUnitTest.java |    4 +-
 .../cache/locks/TXLockServiceDUnitTest.java     |    4 +-
 .../management/CacheManagementDUnitTest.java    | 1001 +++++-----
 .../management/ClientHealthStatsDUnitTest.java  |  574 +++---
 .../management/CompositeTypeTestDUnitTest.java  |  191 +-
 .../management/DLockManagementDUnitTest.java    |  543 ++----
 .../management/DiskManagementDUnitTest.java     |  787 +++-----
 .../management/DistributedSystemDUnitTest.java  |  993 ++++------
 .../geode/management/JMXMBeanDUnitTest.java     |    2 +-
 .../management/LocatorManagementDUnitTest.java  |   13 +-
 .../geode/management/ManagementTestBase.java    |  544 ++----
 .../geode/management/ManagementTestRule.java    |  437 +++++
 .../org/apache/geode/management/Manager.java    |   29 +
 .../org/apache/geode/management/Member.java     |   29 +
 .../management/OffHeapManagementDUnitTest.java  |  347 ++--
 .../geode/management/QueryDataDUnitTest.java    | 1320 ++++++-------
 .../management/RegionManagementDUnitTest.java   | 1839 ++++++++----------
 .../stats/DistributedSystemStatsDUnitTest.java  |  118 +-
 .../QueryDataFunctionApplyLimitClauseTest.java  |    1 -
 .../internal/pulse/TestClientIdsDUnitTest.java  |  315 +--
 .../pulse/TestSubscriptionsDUnitTest.java       |  288 +--
 .../geode/test/dunit/AsyncInvocation.java       |   56 +-
 .../org/apache/geode/test/dunit/Invoke.java     |    6 +-
 .../java/org/apache/geode/test/dunit/VM.java    |    7 +-
 .../java/org/apache/geode/test/dunit/Wait.java  |    2 +
 .../cache/internal/JUnit4CacheTestCase.java     |    5 +
 .../internal/JUnit4DistributedTestCase.java     |    4 +-
 .../dunit/rules/DistributedDisconnectRule.java  |    4 +-
 .../DistributedRestoreSystemProperties.java     |    4 +-
 .../geode/test/dunit/rules/DistributedRule.java |   66 +
 .../test/dunit/rules/DistributedRunRules.java   |   76 +
 .../test/dunit/rules/DistributedStatement.java  |   75 +
 .../test/dunit/rules/DistributedTestRule.java   |  200 ++
 .../DistributedUseJacksonForJsonPathRule.java   |   50 +
 .../dunit/rules/DistributedWrapperRule.java     |   51 +
 .../geode/test/dunit/rules/RemoteInvoker.java   |   16 +-
 .../apache/geode/test/dunit/rules/WhichVMs.java |   59 +
 .../rules/tests/DistributedTestRuleTest.java    |   53 +
 .../test/dunit/standalone/DUnitLauncher.java    |   43 +-
 geode-junit/build.gradle                        |    1 +
 .../junit/rules/UseJacksonForJsonPathRule.java  |  128 ++
 .../SerializableExternalResource.java           |   22 +
 .../serializable/SerializableStatement.java     |   25 +
 .../management/LuceneManagementDUnitTest.java   |   23 +-
 gradle/dependency-versions.properties           |    3 +-
 52 files changed, 4912 insertions(+), 5506 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-assembly/src/test/java/org/apache/geode/rest/internal/web/controllers/RestAPIsAndInterOpsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/rest/internal/web/controllers/RestAPIsAndInterOpsDUnitTest.java b/geode-assembly/src/test/java/org/apache/geode/rest/internal/web/controllers/RestAPIsAndInterOpsDUnitTest.java
index c90a7a4..1802140 100644
--- a/geode-assembly/src/test/java/org/apache/geode/rest/internal/web/controllers/RestAPIsAndInterOpsDUnitTest.java
+++ b/geode-assembly/src/test/java/org/apache/geode/rest/internal/web/controllers/RestAPIsAndInterOpsDUnitTest.java
@@ -65,7 +65,6 @@ import org.apache.geode.distributed.DistributedSystem;
 import org.apache.geode.internal.AvailablePort;
 import org.apache.geode.internal.AvailablePortHelper;
 import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.management.ManagementTestBase;
 import org.apache.geode.pdx.PdxInstance;
 import org.apache.geode.test.dunit.Host;
 import org.apache.geode.test.dunit.NetworkUtils;
@@ -78,28 +77,14 @@ import org.apache.geode.test.junit.runners.CategoryWithParameterizedRunnerFactor
  *
  * @since GemFire 8.0
  */
-
 @Category(DistributedTest.class)
 @RunWith(Parameterized.class)
 @Parameterized.UseParametersRunnerFactory(CategoryWithParameterizedRunnerFactory.class)
+@SuppressWarnings("serial")
 public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
 
-  private static final long serialVersionUID = -254776154266339226L;
-
-  @Parameterized.Parameter
-  public String urlContext;
-
-  @Parameterized.Parameters
-  public static Collection<String> data() {
-    return Arrays.asList("/geode", "/gemfire-api");
-  }
-
-  private ManagementTestBase helper;
-
   public static final String PEOPLE_REGION_NAME = "People";
 
-  // private static RestTemplate restTemplate;
-
   private static final String findAllPeopleQuery =
       "/queries?id=findAllPeople&q=SELECT%20*%20FROM%20/People";
   private static final String findPeopleByGenderQuery =
@@ -161,23 +146,12 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
       + " \"lastName\": \"Patel\"," + " \"birthDate\": \"23/08/2012\"," + "\"gender\": \"MALE\""
       + "}" + "]";
 
-  public RestAPIsAndInterOpsDUnitTest() {
-    super();
-    this.helper = new ManagementTestBase() {
-      {
-      }
-    };
-
-  }
-
-  @Override
-  public final void preSetUp() throws Exception {
-    disconnectAllFromDS();
-  }
+  @Parameterized.Parameter
+  public String urlContext;
 
-  @Override
-  protected final void postTearDownLocatorTestBase() throws Exception {
-    disconnectAllFromDS();
+  @Parameterized.Parameters
+  public static Collection<String> data() {
+    return Arrays.asList("/geode", "/gemfire-api");
   }
 
   public String startBridgeServerWithRestService(final String hostName, final String[] groups,
@@ -828,14 +802,6 @@ public class RestAPIsAndInterOpsDUnitTest extends LocatorTestBase {
 
     // Querying
     doQueryOpsUsingRestApis(restEndpoint);
-
-    // stop the client and make sure the bridge server notifies
-    // stopBridgeMemberVM(client);
-    helper.closeCache(locator);
-    helper.closeCache(manager);
-    helper.closeCache(server);
-    helper.closeCache(client);
-
   }
 
   private void createClientCache(final String host, final int port) throws Exception {

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/build.gradle
----------------------------------------------------------------------
diff --git a/geode-core/build.gradle b/geode-core/build.gradle
index 49dd84b..35b7fa1 100755
--- a/geode-core/build.gradle
+++ b/geode-core/build.gradle
@@ -117,6 +117,7 @@ dependencies {
 
   // Test Dependencies
   // External
+  testCompile 'com.jayway.jsonpath:json-path-assert:' + project.'json-path-assert.version'
   testCompile 'org.apache.bcel:bcel:' + project.'bcel.version'
   testRuntime 'org.apache.derby:derby:' + project.'derby.version'
   testCompile 'org.mockito:mockito-core:' + project.'mockito-core.version'

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/main/java/org/apache/geode/management/JVMMetrics.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/JVMMetrics.java b/geode-core/src/main/java/org/apache/geode/management/JVMMetrics.java
index 127592a..388c8f6 100644
--- a/geode-core/src/main/java/org/apache/geode/management/JVMMetrics.java
+++ b/geode-core/src/main/java/org/apache/geode/management/JVMMetrics.java
@@ -15,6 +15,7 @@
 package org.apache.geode.management;
 
 import java.beans.ConstructorProperties;
+import java.io.Serializable;
 
 import org.apache.geode.cache.Region;
 
@@ -25,7 +26,7 @@ import org.apache.geode.cache.Region;
  * @since GemFire 7.0
  *
  */
-public class JVMMetrics {
+public class JVMMetrics implements Serializable {
 
   /**
    * Number of GCs performed

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/main/java/org/apache/geode/management/OSMetrics.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/OSMetrics.java b/geode-core/src/main/java/org/apache/geode/management/OSMetrics.java
index d90c8be..c9de92f 100644
--- a/geode-core/src/main/java/org/apache/geode/management/OSMetrics.java
+++ b/geode-core/src/main/java/org/apache/geode/management/OSMetrics.java
@@ -15,6 +15,7 @@
 package org.apache.geode.management;
 
 import java.beans.ConstructorProperties;
+import java.io.Serializable;
 
 /**
  * Composite data type used to distribute metrics for the operating system hosting a member of the
@@ -23,7 +24,7 @@ import java.beans.ConstructorProperties;
  * @since GemFire 7.0
  *
  */
-public class OSMetrics {
+public class OSMetrics implements Serializable {
 
   /**
    * Maximum number file descriptor which can be opened

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/main/java/org/apache/geode/management/internal/SystemManagementService.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/SystemManagementService.java b/geode-core/src/main/java/org/apache/geode/management/internal/SystemManagementService.java
index cb75591..fe0f59f 100755
--- a/geode-core/src/main/java/org/apache/geode/management/internal/SystemManagementService.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/SystemManagementService.java
@@ -350,7 +350,8 @@ public final class SystemManagementService extends BaseManagementService {
   }
 
 
-  public <T> T getMBeanProxy(ObjectName objectName, Class<T> interfaceClass) {
+  public <T> T getMBeanProxy(ObjectName objectName, Class<T> interfaceClass) { // TODO: this is too
+                                                                               // generic
     if (!isStartedAndOpen()) {
       return null;
     }

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/distributed/DistributedLockServiceDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/distributed/DistributedLockServiceDUnitTest.java b/geode-core/src/test/java/org/apache/geode/distributed/DistributedLockServiceDUnitTest.java
index 277c604..9a889ca 100755
--- a/geode-core/src/test/java/org/apache/geode/distributed/DistributedLockServiceDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/distributed/DistributedLockServiceDUnitTest.java
@@ -98,7 +98,7 @@ public class DistributedLockServiceDUnitTest extends JUnit4DistributedTestCase {
   @Override
   public final void preTearDown() throws Exception {
     Invoke.invokeInEveryVM(() -> destroyAllDLockServices());
-    // invokeInEveryVM(DistributedLockServiceDUnitTest.class,
+    // invokeInEveryVMAndController(DistributedLockServiceDUnitTest.class,
     // "remoteDumpAllDLockServices");
 
     // InternalDistributedLockService.destroyAll();

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/internal/cache/ConnectDisconnectDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/ConnectDisconnectDUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/ConnectDisconnectDUnitTest.java
index de63433..5213ebc 100755
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/ConnectDisconnectDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/ConnectDisconnectDUnitTest.java
@@ -40,7 +40,7 @@ public class ConnectDisconnectDUnitTest extends JUnit4CacheTestCase {
   // see bugs #50785 and #46438
   @Test
   public void testManyConnectsAndDisconnects() throws Throwable {
-    // invokeInEveryVM(new SerializableRunnable() {
+    // invokeInEveryVMAndController(new SerializableRunnable() {
     //
     // @Override
     // public void run() {

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/internal/cache/PartitionedRegionBucketCreationDistributionDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/PartitionedRegionBucketCreationDistributionDUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/PartitionedRegionBucketCreationDistributionDUnitTest.java
index ed23f2a..82498df 100755
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/PartitionedRegionBucketCreationDistributionDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/PartitionedRegionBucketCreationDistributionDUnitTest.java
@@ -443,9 +443,7 @@ public class PartitionedRegionBucketCreationDistributionDUnitTest
       }
     });
 
-    // final int bucketPerHost = (int) Math.ceil(((double) maxBuckets / Host.getHostCount()));
-
-    // invokeInEveryVM(new SerializableRunnable("") {
+    // invokeInEveryVMAndController(new SerializableRunnable("") {
     //
     // }
 

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/internal/cache/locks/TXLockServiceDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/internal/cache/locks/TXLockServiceDUnitTest.java b/geode-core/src/test/java/org/apache/geode/internal/cache/locks/TXLockServiceDUnitTest.java
index 14267a4..054ab3b 100644
--- a/geode-core/src/test/java/org/apache/geode/internal/cache/locks/TXLockServiceDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/internal/cache/locks/TXLockServiceDUnitTest.java
@@ -89,7 +89,7 @@ public class TXLockServiceDUnitTest extends JUnit4DistributedTestCase {
 
   @Override
   public final void preTearDown() throws Exception {
-    // invokeInEveryVM(TXLockServiceDUnitTest.class,
+    // invokeInEveryVMAndController(TXLockServiceDUnitTest.class,
     // "remoteDumpAllDLockServices");
 
     Invoke.invokeInEveryVM(TXLockServiceDUnitTest.class, "destroyServices");
@@ -114,7 +114,7 @@ public class TXLockServiceDUnitTest extends JUnit4DistributedTestCase {
   public void testGetAndDestroy() {
     forEachVMInvoke("checkGetAndDestroy", new Object[] {});
     /*
-     * invokeInEveryVM(TXLockServiceDUnitTest.class, "destroyServices");
+     * invokeInEveryVMAndController(TXLockServiceDUnitTest.class, "destroyServices");
      * forEachVMInvoke("checkGetAndDestroy", new Object[] {});
      */
   }

http://git-wip-us.apache.org/repos/asf/geode/blob/a409b5a2/geode-core/src/test/java/org/apache/geode/management/CacheManagementDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/CacheManagementDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/CacheManagementDUnitTest.java
index 680579d..62d0b9b 100644
--- a/geode-core/src/test/java/org/apache/geode/management/CacheManagementDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/CacheManagementDUnitTest.java
@@ -14,11 +14,14 @@
  */
 package org.apache.geode.management;
 
-import static org.apache.geode.distributed.ConfigurationProperties.*;
 import static com.jayway.awaitility.Awaitility.*;
+import static java.util.concurrent.TimeUnit.*;
+import static org.apache.geode.distributed.ConfigurationProperties.*;
+import static org.assertj.core.api.Assertions.*;
 import static org.hamcrest.Matchers.*;
-import static org.junit.Assert.*;
 
+import java.io.Serializable;
+import java.lang.management.ManagementFactory;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -26,13 +29,16 @@ import java.util.List;
 import java.util.Map;
 import java.util.Properties;
 import java.util.Set;
-import java.util.concurrent.TimeUnit;
-import javax.management.InstanceNotFoundException;
+
 import javax.management.JMException;
 import javax.management.Notification;
 import javax.management.NotificationListener;
 import javax.management.ObjectName;
 
+import com.jayway.awaitility.Awaitility;
+import com.jayway.awaitility.core.ConditionFactory;
+import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
@@ -43,57 +49,72 @@ import org.apache.geode.cache.RegionShortcut;
 import org.apache.geode.distributed.DistributedMember;
 import org.apache.geode.distributed.internal.DistributionConfig;
 import org.apache.geode.distributed.internal.InternalDistributedSystem;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
+import org.apache.geode.management.internal.LocalManager;
 import org.apache.geode.management.internal.MBeanJMXAdapter;
 import org.apache.geode.management.internal.ManagementConstants;
 import org.apache.geode.management.internal.NotificationHub.NotificationHubListener;
 import org.apache.geode.management.internal.SystemManagementService;
-import org.apache.geode.test.dunit.AsyncInvocation;
-import org.apache.geode.test.dunit.LogWriterUtils;
-import org.apache.geode.test.dunit.SerializableRunnable;
+import org.apache.geode.test.dunit.Invoke;
 import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.Wait;
-import org.apache.geode.test.dunit.WaitCriterion;
 import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
+import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
 
 /**
  * This class checks and verifies various data and operations exposed through MemberMXBean
  * interface.
  * <p>
+ * <p>
  * Goal of the Test : MemberMBean gets created once cache is created. Data like config data and
  * stats are of proper value To check proper federation of MemberMBean including remote ops and
  * remote data access
+ * <p>
+ * <p>
+ * This test is a mess and needs to be rewritten.
  */
 @Category(DistributedTest.class)
-public class CacheManagementDUnitTest extends ManagementTestBase {
+@SuppressWarnings({"serial", "unused"})
+public class CacheManagementDUnitTest implements Serializable {
+
+  /** used in memberVMs */
+  private static final String NOTIFICATION_REGION_NAME = "NotifTestRegion_";
+
+  /** used in managerVM */
+  private static final List<Notification> notifications = new ArrayList<>();
 
-  private final String VERIFY_CONFIG_METHOD = "verifyConfigData";
+  @Manager
+  private VM managerVM;
 
-  private final String VERIFY_REMOTE_CONFIG_METHOD = "verifyConfigDataRemote";
+  @Member
+  private VM[] memberVMs;
 
-  static final List<Notification> notifList = new ArrayList<Notification>();
+  @Rule
+  public ManagementTestRule managementTestRule = ManagementTestRule.builder().build();
 
-  // This must be bigger than the dunit ack-wait-threshold for the revoke
-  // tests. The command line is setting the ack-wait-threshold to be
-  // 60 seconds.
-  private static final int MAX_WAIT = 70 * 1000;
+  @Rule
+  public SerializableTemporaryFolder temporaryFolder = new SerializableTemporaryFolder();
+
+  @Rule
+  public SerializableTestName testName = new SerializableTestName();
+
+  @Before
+  public void before() throws Exception {
+    this.managerVM.invoke(() -> notifications.clear());
+  }
 
   @Test
   public void testGemFireConfigData() throws Exception {
-    initManagement(false);
+    this.managementTestRule.createMembers();
+    this.managementTestRule.createManagers();
 
-    Map<DistributedMember, DistributionConfig> configMap =
-        new HashMap<DistributedMember, DistributionConfig>();
-    for (VM vm : getManagedNodeList()) {
+    Map<DistributedMember, DistributionConfig> configMap = new HashMap<>();
+    for (VM memberVM : this.memberVMs) {
       Map<DistributedMember, DistributionConfig> configMapMember =
-          (Map<DistributedMember, DistributionConfig>) vm.invoke(CacheManagementDUnitTest.class,
-              VERIFY_CONFIG_METHOD);
+          memberVM.invoke(() -> verifyConfigData());
       configMap.putAll(configMapMember);
     }
 
-    Object[] args = new Object[1];
-    args[0] = configMap;
-    getManagingNode().invoke(CacheManagementDUnitTest.class, VERIFY_REMOTE_CONFIG_METHOD, args);
+    this.managerVM.invoke(() -> verifyConfigDataRemote(configMap));
   }
 
   /**
@@ -101,30 +122,35 @@ public class CacheManagementDUnitTest extends ManagementTestBase {
    */
   @Test
   public void testMemberMBeanOperations() throws Exception {
-    initManagement(false);
+    int i = 1;
+    for (VM memberVM : this.memberVMs) {
+      Properties props = new Properties();
+      props.setProperty(LOG_FILE, this.temporaryFolder
+          .newFile(this.testName.getMethodName() + "-VM" + i + ".log").getAbsolutePath());
+      this.managementTestRule.createMember(memberVM, props);
+      i++;
+    }
 
-    for (VM vm : managedNodeList) {
+    this.managementTestRule.createManagers();
 
-      // Do some operations to fill the logs
+    for (VM memberVM : this.memberVMs) {
+      String logMessage = "This line should be in the log";
+      memberVM.invoke(() -> this.managementTestRule.getCache().getLogger().info(logMessage));
 
-      createLocalRegion(vm, "testRegion");
+      String log = memberVM.invoke(() -> fetchLog(30));
+      assertThat(log).isNotNull();
+      assertThat(log).contains(logMessage);
 
-      String log = (String) vm.invoke(() -> CacheManagementDUnitTest.fetchLog());
-      assertNotNull(log);
-      LogWriterUtils.getLogWriter()
-          .info("<ExpectedString> Log Of Member is " + log.toString() + "</ExpectedString> ");
+      JVMMetrics jvmMetrics = memberVM.invoke(() -> fetchJVMMetrics());
 
-      vm.invoke(() -> CacheManagementDUnitTest.fetchJVMMetrics());
+      OSMetrics osMetrics = memberVM.invoke(() -> fetchOSMetrics());
 
-      vm.invoke(() -> CacheManagementDUnitTest.fetchOSMetrics());
+      // TODO: need assertions
 
-      vm.invoke(() -> CacheManagementDUnitTest.shutDownMember());
+      memberVM.invoke(() -> shutDownMember());
     }
 
-    VM managingNode = getManagingNode();
-    Object[] args = new Object[1];
-    args[0] = 1;// Only locator member wont be shutdown
-    managingNode.invoke(CacheManagementDUnitTest.class, "assertExpectedMembers", args);
+    this.managerVM.invoke(() -> verifyExpectedMembers(0));
   }
 
   /**
@@ -132,270 +158,259 @@ public class CacheManagementDUnitTest extends ManagementTestBase {
    */
   @Test
   public void testMemberMBeanOpsRemote() throws Exception {
-    initManagement(false);
-    getManagingNode().invoke(() -> CacheManagementDUnitTest.invokeRemoteOps());
+    this.managementTestRule.createMembers();
+    this.managementTestRule.createManagers();
+    this.managerVM.invoke(() -> invokeRemoteMemberMXBeanOps());
   }
 
   /**
-   * Creates and starts a manager. Multiple Managers
+   * Creates and starts a managerVM. Multiple Managers
    */
   @Test
   public void testManager() throws Exception {
-    List<VM> managedNodeList = getManagedNodeList();
-    VM node1 = managedNodeList.get(0);
-    VM node2 = managedNodeList.get(1);
-    VM node3 = managedNodeList.get(2);
-    VM managingNode = getManagingNode();
+    this.managementTestRule.createMember(this.memberVMs[0]);
+    this.managementTestRule.createMember(this.memberVMs[1]);
 
-    createCache(node1);
-    createCache(node2);
-    createManagementCache(node3);
+    this.managementTestRule.createManager(this.memberVMs[2], false);
 
-    // Only creates a cache in Managing Node
-    // Does not start the manager
-    createManagementCache(managingNode);
+    this.managementTestRule.createManager(this.managerVM, false);
 
-    node3.invoke(() -> CacheManagementDUnitTest.startManager());
+    this.memberVMs[2].invoke(() -> startManager());
 
-    // Now start Managing node manager. System will have two Managers now which
+    // Now start Managing node managerVM. System will have two Managers now which
     // should be OK
-    DistributedMember member = getMember(node3);
-    startManagingNode(managingNode);
-    checkManagerView(managingNode, member);
-    stopManagingNode(managingNode);
+    DistributedMember member = this.managementTestRule.getDistributedMember(this.memberVMs[2]);
+    this.managementTestRule.startManager(this.managerVM);
+
+    verifyManagerStarted(this.managerVM, member);
+    this.managementTestRule.stopManager(this.managerVM);
   }
 
   /**
-   * Creates and starts a manager. Multiple Managers
+   * Creates and starts a managerVM. Multiple Managers
    */
   @Test
   public void testManagerShutdown() throws Exception {
-    List<VM> managedNodeList = getManagedNodeList();
-    VM node1 = managedNodeList.get(0);
-    VM node2 = managedNodeList.get(1);
-    VM node3 = managedNodeList.get(2);
-    VM managingNode = getManagingNode();
+    this.managementTestRule.createMember(this.memberVMs[0]);
+    this.managementTestRule.createMember(this.memberVMs[1]);
+    this.managementTestRule.createMember(this.memberVMs[2]);
 
-    createCache(node1);
-    createCache(node2);
-    createCache(node3);
+    this.managementTestRule.createManager(this.managerVM, false);
+    this.managementTestRule.startManager(this.managerVM);
 
-    // Only creates a cache in Managing Node
-    // Does not start the manager
-    createManagementCache(managingNode);
+    verifyManagerStarted(this.managerVM,
+        this.managementTestRule.getDistributedMember(this.memberVMs[0]));
 
-    startManagingNode(managingNode);
-    DistributedMember member = getMember(managingNode);
-    checkManagerView(managingNode, member);
-    stopManagingNode(managingNode);
-    checkNonManagerView(managingNode);
+    this.managementTestRule.stopManager(this.managerVM);
+    verifyManagerStopped(this.managerVM, this.memberVMs.length);
   }
 
   @Test
-  public void testServiceCloseManagedNode() throws Exception {
-    List<VM> managedNodeList = getManagedNodeList();
-    VM node1 = managedNodeList.get(0);
-    VM node2 = managedNodeList.get(1);
-    VM node3 = managedNodeList.get(2);
-    VM managingNode = getManagingNode();
+  public void closeCacheShouldStopLocalManager() throws Exception {
+    this.managementTestRule.createMember(this.memberVMs[0]);
+    this.managementTestRule.createMember(this.memberVMs[1]);
 
-    createCache(node1);
-    createCache(node2);
-    createManagementCache(node3);
+    this.managementTestRule.createManager(this.memberVMs[2], false);
 
     // Only creates a cache in Managing Node
-    // Does not start the manager
-    createManagementCache(managingNode);
-
-    node3.invoke(() -> CacheManagementDUnitTest.startManager());
-
-    closeCache(node3);
-    validateServiceResource(node3);
+    // Does not start the managerVM
+    this.managementTestRule.createManager(this.managerVM, false);
+
+    this.memberVMs[2].invoke(() -> startManager());
+
+    this.memberVMs[2].invoke(() -> {
+      SystemManagementService service = this.managementTestRule.getSystemManagementService();
+      LocalManager localManager = service.getLocalManager();
+      this.managementTestRule.getCache().close();
+      assertThat(localManager.isRunning()).isFalse();
+      assertThat(service.isManager()).isFalse();
+      assertThat(service.getLocalManager()).isNull();
+    });
   }
 
   @Test
   public void testGetMBean() throws Exception {
-    List<VM> managedNodeList = getManagedNodeList();
-    VM node1 = managedNodeList.get(0);
-    VM node2 = managedNodeList.get(1);
-    VM node3 = managedNodeList.get(2);
-    VM managingNode = getManagingNode();
+    this.managementTestRule.createMember(this.memberVMs[0]);
+    this.managementTestRule.createMember(this.memberVMs[1]);
+    this.managementTestRule.createMember(this.memberVMs[2]);
 
-    createCache(node1);
-    createCache(node2);
-    createCache(node3);
+    this.managementTestRule.createManager(this.managerVM, false);
 
-    createManagementCache(managingNode);
+    this.managementTestRule.startManager(this.managerVM);
 
-    startManagingNode(managingNode);
-
-    checkGetMBean(managingNode);
+    verifyGetMBeanInstance(this.managerVM);
   }
 
   @Test
   public void testQueryMBeans() throws Exception {
-    List<VM> managedNodeList = getManagedNodeList();
-    VM node1 = managedNodeList.get(0);
-    VM node2 = managedNodeList.get(1);
-    VM node3 = managedNodeList.get(2);
-    VM managingNode = getManagingNode();
-
-    createCache(node1);
-    createCache(node2);
-    createCache(node3);
+    this.managementTestRule.createMember(this.memberVMs[0]);
+    this.managementTestRule.createMember(this.memberVMs[1]);
+    this.managementTestRule.createMember(this.memberVMs[2]);
 
-    createManagementCache(managingNode);
+    this.managementTestRule.createManager(this.managerVM, false);
 
-    startManagingNode(managingNode);
+    this.managementTestRule.startManager(this.managerVM);
 
-    checkQueryMBeans(managingNode);
+    verifyQueryMBeans(this.managerVM);
   }
 
-  protected void checkQueryMBeans(final VM vm) {
-    SerializableRunnable validateServiceResource = new SerializableRunnable("Check Query MBeans") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
+  @Test
+  public void testNotification() throws Exception {
+    // Step : 1 : Create Managed Node Caches
+    this.managementTestRule.createMember(this.memberVMs[0]);
+    this.managementTestRule.createMember(this.memberVMs[1]);
+    this.managementTestRule.createMember(this.memberVMs[2]);
 
-        Set<DistributedMember> otherMembers =
-            cache.getDistributionManager().getOtherNormalDistributionManagerIds();
+    // Step : 2 : Create Managing Node Cache, start managerVM, add a notification
+    // handler to DistributedSystemMXBean
+    this.managementTestRule.createManager(this.managerVM, false);
+    this.managementTestRule.startManager(this.managerVM);
+    attachListenerToDistributedSystemMXBean(this.managerVM);
 
-        Set<ObjectName> superSet = new HashSet<ObjectName>();
+    // Step : 3 : Verify Notification count, notification region sizes
+    verifyNotificationsAndRegionSize(this.memberVMs[0], this.memberVMs[1], this.memberVMs[2],
+        this.managerVM);
+  }
 
-        for (DistributedMember member : otherMembers) {
+  @Test
+  public void testNotificationManagingNodeFirst() throws Exception {
+    // Step : 1 : Create Managing Node Cache, start managerVM, add a notification
+    // handler to DistributedSystemMXBean
+    this.managementTestRule.createManager(this.managerVM, false);
+    this.managementTestRule.startManager(this.managerVM);
 
-          ObjectName memberMBeanName = managementService.getMemberMBeanName(member);
+    attachListenerToDistributedSystemMXBean(this.managerVM);
 
-          waitForProxy(memberMBeanName, MemberMXBean.class);
-          Set<ObjectName> names = managementService.queryMBeanNames(member);
-          superSet.addAll(names);
-          assertTrue(names.contains(memberMBeanName));
+    // Step : 2 : Create Managed Node Caches
+    this.managementTestRule.createMember(this.memberVMs[0]);
+    this.managementTestRule.createMember(this.memberVMs[1]);
+    this.managementTestRule.createMember(this.memberVMs[2]);
 
-        }
+    // Step : 3 : Verify Notification count, notification region sizes
+    verifyNotificationsAndRegionSize(this.memberVMs[0], this.memberVMs[1], this.memberVMs[2],
+        this.managerVM);
+  }
 
-        Set<ObjectName> names =
-            managementService.queryMBeanNames(cache.getDistributedSystem().getDistributedMember());
-        assertTrue(!superSet.contains(names));
-      }
-    };
-    vm.invoke(validateServiceResource);
+  @Test
+  public void testRedundancyZone() throws Exception {
+    String redundancyZone = "ARMY_ZONE";
+
+    Properties props = new Properties();
+    props.setProperty(REDUNDANCY_ZONE, redundancyZone);
+
+    this.managementTestRule.createMember(this.memberVMs[0], props);
 
+    this.memberVMs[0].invoke("verifyRedundancyZone", () -> {
+      ManagementService service = this.managementTestRule.getExistingManagementService();
+      MemberMXBean memberMXBean = service.getMemberMXBean();
+      assertThat(memberMXBean.getRedundancyZone()).isEqualTo(redundancyZone);
+    });
   }
 
-  protected void checkGetMBean(final VM vm) {
-    SerializableRunnable validateServiceResource = new SerializableRunnable("Check Get MBean") {
-      public void run() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Set<DistributedMember> otherMembers =
-            cache.getDistributionManager().getOtherNormalDistributionManagerIds();
+  private void verifyQueryMBeans(final VM vm) {
+    vm.invoke("validateQueryMBeans", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      Set<DistributedMember> otherMembers = this.managementTestRule.getOtherNormalMembers();
+      Set<ObjectName> superSet = new HashSet<>();
+
+      for (DistributedMember member : otherMembers) {
+        ObjectName memberMBeanName = service.getMemberMBeanName(member);
 
-        for (DistributedMember member : otherMembers) {
+        awaitMemberMXBeanProxy(member);
 
-          ObjectName memberMBeanName = managementService.getMemberMBeanName(member);
+        Set<ObjectName> objectNames = service.queryMBeanNames(member);
+        superSet.addAll(objectNames);
+        assertThat(objectNames.contains(memberMBeanName)).isTrue();
+      }
 
-          waitForProxy(memberMBeanName, MemberMXBean.class);
+      Set<ObjectName> names =
+          service.queryMBeanNames(this.managementTestRule.getDistributedMember());
+      ObjectName[] arrayOfNames = names.toArray(new ObjectName[names.size()]);
 
-          MemberMXBean bean =
-              managementService.getMBeanInstance(memberMBeanName, MemberMXBean.class);
-          assertNotNull(bean);
-        }
+      assertThat(superSet).doesNotContain(arrayOfNames); // TODO: what value does this method have?
+    });
+  }
+
+  private void verifyGetMBeanInstance(final VM vm) {
+    vm.invoke("verifyGetMBeanInstance", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      Set<DistributedMember> otherMembers = this.managementTestRule.getOtherNormalMembers();
+
+      for (DistributedMember member : otherMembers) {
+        ObjectName memberMBeanName = service.getMemberMBeanName(member);
 
-        DistributedMember thisMember = cache.getDistributedSystem().getDistributedMember();
-        ObjectName memberMBeanName = managementService.getMemberMBeanName(thisMember);
-        MemberMXBean bean = managementService.getMBeanInstance(memberMBeanName, MemberMXBean.class);
-        assertNotNull(bean);
+        awaitMemberMXBeanProxy(member);
 
+        MemberMXBean memberMXBean = service.getMBeanInstance(memberMBeanName, MemberMXBean.class);
+        assertThat(memberMXBean).isNotNull();
       }
-    };
-    vm.invoke(validateServiceResource);
+
+      DistributedMember distributedMember = this.managementTestRule.getDistributedMember();
+      ObjectName memberMBeanName = service.getMemberMBeanName(distributedMember);
+      MemberMXBean memberMXBean = service.getMBeanInstance(memberMBeanName, MemberMXBean.class);
+      assertThat(memberMXBean).isNotNull();
+    });
   }
 
-  protected void validateServiceResource(final VM vm) {
-    SerializableRunnable validateServiceResource =
-        new SerializableRunnable("Valideate Management Service Resource") {
-          public void run() {
+  private void verifyManagerStarted(final VM managerVM, final DistributedMember otherMember) {
+    managerVM.invoke("verifyManagerStarted", () -> {
+      SystemManagementService service = this.managementTestRule.getSystemManagementService();
+      assertThat(service.isManager()).isTrue();
 
-            GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-            assertNull(cache);
-            assertFalse(managementService.isManager());
+      assertThat(service.getLocalManager().isRunning()).isTrue();
 
-            SystemManagementService service = (SystemManagementService) managementService;
-            assertNull(service.getLocalManager());
-          }
-        };
-    vm.invoke(validateServiceResource);
-  }
+      assertThat(service.getLocalManager().getFederationSheduler().isShutdown()).isFalse();
 
-  /**
-   * Creates a Distributed Region
-   */
-  protected AsyncInvocation checkManagerView(final VM vm, final DistributedMember oneManager) {
-    SerializableRunnable createRegion = new SerializableRunnable("Check Manager View") {
-      public void run() {
-
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-        ObjectName memberMBeanName = service.getMemberMBeanName(oneManager);
-        MemberMXBean bean = service.getMBeanProxy(memberMBeanName, MemberMXBean.class);
-        assertNotNull(bean);
-        // Ensure Data getting federated from Managing node
-        long t1 = bean.getMemberUpTime();
-        try {
-          this.wait(ManagementConstants.REFRESH_TIME * 3);
-        } catch (InterruptedException e) {
-          fail("interrupted");
-        }
-        long t2 = bean.getMemberUpTime();
+      ObjectName memberMBeanName = service.getMemberMBeanName(otherMember);
 
-        assertTrue(t2 > t1);
+      await().until(
+          () -> assertThat(service.getMBeanProxy(memberMBeanName, MemberMXBean.class)).isNotNull());
+      MemberMXBean memberMXBean = service.getMBeanProxy(memberMBeanName, MemberMXBean.class);
 
-      }
-    };
-    return vm.invokeAsync(createRegion);
+      // Ensure Data getting federated from Managing node
+      long start = memberMXBean.getMemberUpTime();
+      await().until(() -> assertThat(memberMXBean.getMemberUpTime()).isGreaterThan(start));
+    });
   }
 
   /**
    * Add any Manager clean up asserts here
    */
-  protected void checkNonManagerView(final VM vm) {
-    SerializableRunnable checkNonManagerView = new SerializableRunnable("Check Non Manager View") {
-      public void run() {
-
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        assertNotNull(cache);
-        assertFalse(managementService.isManager());
-
-        SystemManagementService service = (SystemManagementService) managementService;
-        assertTrue(service.getLocalManager().isRunning());
-        assertFalse(service.getLocalManager().getFederationSheduler().isShutdown());
-
-        // Check for Proxies
-        Set<DistributedMember> otherMembers =
-            cache.getDistributionManager().getOtherNormalDistributionManagerIds();
-        assertTrue(otherMembers.size() > 0);
-        for (DistributedMember member : otherMembers) {
-          Set<ObjectName> proxyNames =
-              service.getFederatingManager().getProxyFactory().findAllProxies(member);
-          assertTrue(proxyNames.isEmpty());
-          ObjectName proxyMBeanName = service.getMemberMBeanName(member);
-          assertFalse(MBeanJMXAdapter.mbeanServer.isRegistered(proxyMBeanName));
-        }
+  private void verifyManagerStopped(final VM managerVM, final int otherMembersCount) {
+    managerVM.invoke("verifyManagerStopped", () -> {
+      SystemManagementService service = this.managementTestRule.getSystemManagementService();
+
+      assertThat(service.isManager()).isFalse();
+      assertThat(service.getLocalManager().isRunning()).isTrue();
+      assertThat(service.getLocalManager().getFederationSheduler().isShutdown()).isFalse();
+
+      // Check for Proxies
+      Set<DistributedMember> otherMembers = this.managementTestRule.getOtherNormalMembers();
+      assertThat(otherMembers).hasSize(otherMembersCount);
+
+      for (DistributedMember member : otherMembers) {
+        Set<ObjectName> proxyNames =
+            service.getFederatingManager().getProxyFactory().findAllProxies(member);
+        assertThat(proxyNames).isEmpty();
 
+        ObjectName proxyMBeanName = service.getMemberMBeanName(member);
+        assertThat(MBeanJMXAdapter.mbeanServer.isRegistered(proxyMBeanName)).isFalse();
       }
-    };
-    vm.invoke(checkNonManagerView);
+    });
   }
 
-  public static Map<DistributedMember, DistributionConfig> verifyConfigData() {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    ManagementService service = getManagementService();
-    DistributionConfig config =
-        ((InternalDistributedSystem) cache.getDistributedSystem()).getConfig();
+  private Map<DistributedMember, DistributionConfig> verifyConfigData() {
+    ManagementService service = this.managementTestRule.getManagementService();
+    InternalDistributedSystem ids =
+        (InternalDistributedSystem) this.managementTestRule.getCache().getDistributedSystem();
+    DistributionConfig config = ids.getConfig();
+
     MemberMXBean bean = service.getMemberMXBean();
     GemFireProperties data = bean.listGemFireProperties();
-    assertConfigEquals(config, data);
-    Map<DistributedMember, DistributionConfig> configMap =
-        new HashMap<DistributedMember, DistributionConfig>();
-    configMap.put(cache.getMyId(), config);
+    verifyGemFirePropertiesData(config, data);
+
+    Map<DistributedMember, DistributionConfig> configMap = new HashMap<>();
+    configMap.put(ids.getDistributedMember(), config);
     return configMap;
   }
 
@@ -403,398 +418,276 @@ public class CacheManagementDUnitTest extends ManagementTestBase {
    * This is to check whether the config data has been propagated to the Managing node properly or
    * not.
    */
-  public static void verifyConfigDataRemote(Map<DistributedMember, DistributionConfig> configMap)
+  private void verifyConfigDataRemote(final Map<DistributedMember, DistributionConfig> configMap)
       throws Exception {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    Set<DistributedMember> otherMemberSet =
-        cache.getDistributionManager().getOtherNormalDistributionManagerIds();
+    Set<DistributedMember> otherMembers = this.managementTestRule.getOtherNormalMembers();
 
-    for (DistributedMember member : otherMemberSet) {
-      MemberMXBean bean = MBeanUtil.getMemberMbeanProxy(member);
-      GemFireProperties data = bean.listGemFireProperties();
+    for (DistributedMember member : otherMembers) {
+      MemberMXBean memberMXBean = awaitMemberMXBeanProxy(member);
+
+      GemFireProperties data = memberMXBean.listGemFireProperties();
       DistributionConfig config = configMap.get(member);
-      assertConfigEquals(config, data);
+      verifyGemFirePropertiesData(config, data);
     }
   }
 
   /**
    * Asserts that distribution config and gemfireProperty composite types hold the same values
    */
-  public static void assertConfigEquals(DistributionConfig config, GemFireProperties data) {
+  private void verifyGemFirePropertiesData(final DistributionConfig config,
+      final GemFireProperties data) {
+    assertThat(data.getMemberName()).isEqualTo(config.getName());
 
-    assertEquals(data.getMemberName(), config.getName());
     // **TODO **
     String memberGroups = null;
 
-    assertEquals(data.getMcastPort(), config.getMcastPort());
-    assertEquals(data.getMcastAddress(), config.getMcastAddress().getHostAddress());
-    assertEquals(data.getBindAddress(), config.getBindAddress());
-    assertEquals(data.getTcpPort(), config.getTcpPort());
-    assertEquals(removeVMDir(data.getCacheXMLFile()),
-        removeVMDir(config.getCacheXmlFile().getAbsolutePath()));
+    assertThat(data.getMcastPort()).isEqualTo(config.getMcastPort());
+    assertThat(data.getMcastAddress()).isEqualTo(config.getMcastAddress().getHostAddress());
+    assertThat(data.getBindAddress()).isEqualTo(config.getBindAddress());
+    assertThat(data.getTcpPort()).isEqualTo(config.getTcpPort());
+    assertThat(removeVMDir(data.getCacheXMLFile()))
+        .isEqualTo(removeVMDir(config.getCacheXmlFile().getAbsolutePath()));
+
     // **TODO **
-    assertEquals(data.getMcastTTL(), config.getMcastTtl());
-    assertEquals(data.getServerBindAddress(), config.getServerBindAddress());
-    assertEquals(data.getLocators(), config.getLocators());
+    assertThat(data.getMcastTTL()).isEqualTo(config.getMcastTtl());
+    assertThat(data.getServerBindAddress()).isEqualTo(config.getServerBindAddress());
+    assertThat(data.getLocators()).isEqualTo(config.getLocators());
+
     // The start locator may contain a directory
-    assertEquals(removeVMDir(data.getStartLocator()), removeVMDir(config.getStartLocator()));
-    assertEquals(removeVMDir(data.getLogFile()),
-        removeVMDir(config.getLogFile().getAbsolutePath()));
-    assertEquals(data.getLogLevel(), config.getLogLevel());
-    assertEquals(data.isStatisticSamplingEnabled(), config.getStatisticSamplingEnabled());
-    assertEquals(removeVMDir(data.getStatisticArchiveFile()),
-        removeVMDir(config.getStatisticArchiveFile().getAbsolutePath()));
+    assertThat(removeVMDir(data.getStartLocator()))
+        .isEqualTo(removeVMDir(config.getStartLocator()));
+    assertThat(removeVMDir(data.getLogFile()))
+        .isEqualTo(removeVMDir(config.getLogFile().getAbsolutePath()));
+    assertThat(data.getLogLevel()).isEqualTo(config.getLogLevel());
+    assertThat(data.isStatisticSamplingEnabled()).isEqualTo(config.getStatisticSamplingEnabled());
+    assertThat(removeVMDir(data.getStatisticArchiveFile()))
+        .isEqualTo(removeVMDir(config.getStatisticArchiveFile().getAbsolutePath()));
+
     // ** TODO **
     String includeFile = null;
-    assertEquals(data.getAckWaitThreshold(), config.getAckWaitThreshold());
-    assertEquals(data.getAckSevereAlertThreshold(), config.getAckSevereAlertThreshold());
-    assertEquals(data.getArchiveFileSizeLimit(), config.getArchiveFileSizeLimit());
-    assertEquals(data.getArchiveDiskSpaceLimit(), config.getArchiveDiskSpaceLimit());
-    assertEquals(data.getLogFileSizeLimit(), config.getLogFileSizeLimit());
-    assertEquals(data.getLogDiskSpaceLimit(), config.getLogDiskSpaceLimit());
-    assertEquals(data.isClusterSSLEnabled(), config.getClusterSSLEnabled());
-
-    assertEquals(data.getClusterSSLCiphers(), config.getClusterSSLCiphers());
-    assertEquals(data.getClusterSSLProtocols(), config.getClusterSSLProtocols());
-    assertEquals(data.isClusterSSLRequireAuthentication(),
-        config.getClusterSSLRequireAuthentication());
-    assertEquals(data.getSocketLeaseTime(), config.getSocketLeaseTime());
-    assertEquals(data.getSocketBufferSize(), config.getSocketBufferSize());
-    assertEquals(data.getMcastSendBufferSize(), config.getMcastSendBufferSize());
-    assertEquals(data.getMcastRecvBufferSize(), config.getMcastRecvBufferSize());
-    assertEquals(data.getMcastByteAllowance(), config.getMcastFlowControl().getByteAllowance());
-    assertEquals(data.getMcastRechargeThreshold(),
-        config.getMcastFlowControl().getRechargeThreshold(), 0);
-    assertEquals(data.getMcastRechargeBlockMs(), config.getMcastFlowControl().getRechargeBlockMs());
-    assertEquals(data.getUdpFragmentSize(), config.getUdpFragmentSize());
-    assertEquals(data.getUdpSendBufferSize(), config.getUdpSendBufferSize());
-    assertEquals(data.getUdpRecvBufferSize(), config.getUdpRecvBufferSize());
-    assertEquals(data.isDisableTcp(), config.getDisableTcp());
-    assertEquals(data.isEnableTimeStatistics(), config.getEnableTimeStatistics());
-    assertEquals(data.isEnableNetworkPartitionDetection(),
-        config.getEnableNetworkPartitionDetection());
-    assertEquals(data.getMemberTimeout(), config.getMemberTimeout());
-
-    int[] configPortRange = config.getMembershipPortRange();
-    int[] dataPortRange = data.getMembershipPortRange();
-
-    assertEquals(dataPortRange.length, configPortRange.length);
-    for (int i = 0; i < dataPortRange.length; i++) {
-      assertEquals(dataPortRange[i], configPortRange[i]);
-    }
-    assertEquals(data.isConserveSockets(), config.getConserveSockets());
-    assertEquals(data.getRoles(), config.getRoles());
-    assertEquals(data.getMaxWaitTimeForReconnect(), config.getMaxWaitTimeForReconnect());
-    assertEquals(data.getMaxNumReconnectTries(), config.getMaxNumReconnectTries());
-    assertEquals(data.getAsyncDistributionTimeout(), config.getAsyncDistributionTimeout());
-    assertEquals(data.getAsyncQueueTimeout(), config.getAsyncQueueTimeout());
-    assertEquals(data.getAsyncMaxQueueSize(), config.getAsyncMaxQueueSize());
-    assertEquals(data.getClientConflation(), config.getClientConflation());
-    assertEquals(data.getDurableClientId(), config.getDurableClientId());
-    assertEquals(data.getDurableClientTimeout(), config.getDurableClientTimeout());
-    assertEquals(data.getSecurityClientAuthInit(), config.getSecurityClientAuthInit());
-    assertEquals(data.getSecurityClientAuthenticator(), config.getSecurityClientAuthenticator());
-    assertEquals(data.getSecurityClientDHAlgo(), config.getSecurityClientDHAlgo());
-    assertEquals(data.getSecurityPeerAuthInit(), config.getSecurityPeerAuthInit());
-    assertEquals(data.getSecurityClientAuthenticator(), config.getSecurityPeerAuthenticator());
-    assertEquals(data.getSecurityClientAccessor(), config.getSecurityClientAccessor());
-    assertEquals(data.getSecurityClientAccessorPP(), config.getSecurityClientAccessorPP());
-    assertEquals(data.getSecurityLogLevel(), config.getSecurityLogLevel());
-    assertEquals(removeVMDir(data.getSecurityLogFile()),
-        removeVMDir(config.getSecurityLogFile().getAbsolutePath()));
-    assertEquals(data.getSecurityPeerMembershipTimeout(),
-        config.getSecurityPeerMembershipTimeout());
-    assertEquals(data.isRemoveUnresponsiveClient(), config.getRemoveUnresponsiveClient());
-    assertEquals(data.isDeltaPropagation(), config.getDeltaPropagation());
-    assertEquals(data.getRedundancyZone(), config.getRedundancyZone());
-    assertEquals(data.isEnforceUniqueHost(), config.getEnforceUniqueHost());
-    assertEquals(data.getStatisticSampleRate(), config.getStatisticSampleRate());
+    assertThat(data.getAckWaitThreshold()).isEqualTo(config.getAckWaitThreshold());
+    assertThat(data.getAckSevereAlertThreshold()).isEqualTo(config.getAckSevereAlertThreshold());
+    assertThat(data.getArchiveFileSizeLimit()).isEqualTo(config.getArchiveFileSizeLimit());
+    assertThat(data.getArchiveDiskSpaceLimit()).isEqualTo(config.getArchiveDiskSpaceLimit());
+    assertThat(data.getLogFileSizeLimit()).isEqualTo(config.getLogFileSizeLimit());
+    assertThat(data.getLogDiskSpaceLimit()).isEqualTo(config.getLogDiskSpaceLimit());
+    assertThat(data.isClusterSSLEnabled()).isEqualTo(config.getClusterSSLEnabled());
+
+    assertThat(data.getClusterSSLCiphers()).isEqualTo(config.getClusterSSLCiphers());
+    assertThat(data.getClusterSSLProtocols()).isEqualTo(config.getClusterSSLProtocols());
+    assertThat(data.isClusterSSLRequireAuthentication())
+        .isEqualTo(config.getClusterSSLRequireAuthentication());
+    assertThat(data.getSocketLeaseTime()).isEqualTo(config.getSocketLeaseTime());
+    assertThat(data.getSocketBufferSize()).isEqualTo(config.getSocketBufferSize());
+    assertThat(data.getMcastSendBufferSize()).isEqualTo(config.getMcastSendBufferSize());
+    assertThat(data.getMcastRecvBufferSize()).isEqualTo(config.getMcastRecvBufferSize());
+    assertThat(data.getMcastByteAllowance())
+        .isEqualTo(config.getMcastFlowControl().getByteAllowance());
+    assertThat(data.getMcastRechargeThreshold())
+        .isEqualTo(config.getMcastFlowControl().getRechargeThreshold());
+    assertThat(data.getMcastRechargeBlockMs())
+        .isEqualTo(config.getMcastFlowControl().getRechargeBlockMs());
+    assertThat(data.getUdpFragmentSize()).isEqualTo(config.getUdpFragmentSize());
+    assertThat(data.getUdpSendBufferSize()).isEqualTo(config.getUdpSendBufferSize());
+    assertThat(data.getUdpRecvBufferSize()).isEqualTo(config.getUdpRecvBufferSize());
+    assertThat(data.isDisableTcp()).isEqualTo(config.getDisableTcp());
+    assertThat(data.isEnableTimeStatistics()).isEqualTo(config.getEnableTimeStatistics());
+    assertThat(data.isEnableNetworkPartitionDetection())
+        .isEqualTo(config.getEnableNetworkPartitionDetection());
+    assertThat(data.getMemberTimeout()).isEqualTo(config.getMemberTimeout());
+
+    assertThat(data.getMembershipPortRange()).containsExactly(config.getMembershipPortRange());
+
+    assertThat(data.isConserveSockets()).isEqualTo(config.getConserveSockets());
+    assertThat(data.getRoles()).isEqualTo(config.getRoles());
+    assertThat(data.getMaxWaitTimeForReconnect()).isEqualTo(config.getMaxWaitTimeForReconnect());
+    assertThat(data.getMaxNumReconnectTries()).isEqualTo(config.getMaxNumReconnectTries());
+    assertThat(data.getAsyncDistributionTimeout()).isEqualTo(config.getAsyncDistributionTimeout());
+    assertThat(data.getAsyncMaxQueueSize()).isEqualTo(config.getAsyncMaxQueueSize());
+    assertThat(data.getClientConflation()).isEqualTo(config.getClientConflation());
+    assertThat(data.getDurableClientId()).isEqualTo(config.getDurableClientId());
+    assertThat(data.getDurableClientTimeout()).isEqualTo(config.getDurableClientTimeout());
+    assertThat(data.getSecurityClientAuthInit()).isEqualTo(config.getSecurityClientAuthInit());
+    assertThat(data.getSecurityClientAuthenticator())
+        .isEqualTo(config.getSecurityClientAuthenticator());
+    assertThat(data.getSecurityClientDHAlgo()).isEqualTo(config.getSecurityClientDHAlgo());
+    assertThat(data.getSecurityPeerAuthInit()).isEqualTo(config.getSecurityPeerAuthInit());
+    assertThat(data.getSecurityClientAuthenticator())
+        .isEqualTo(config.getSecurityPeerAuthenticator());
+    assertThat(data.getSecurityClientAccessor()).isEqualTo(config.getSecurityClientAccessor());
+    assertThat(data.getSecurityClientAccessorPP()).isEqualTo(config.getSecurityClientAccessorPP());
+    assertThat(data.getSecurityLogLevel()).isEqualTo(config.getSecurityLogLevel());
+    assertThat(removeVMDir(data.getSecurityLogFile()))
+        .isEqualTo(removeVMDir(config.getSecurityLogFile().getAbsolutePath()));
+    assertThat(data.getSecurityPeerMembershipTimeout())
+        .isEqualTo(config.getSecurityPeerMembershipTimeout());
+    assertThat(data.isRemoveUnresponsiveClient()).isEqualTo(config.getRemoveUnresponsiveClient());
+    assertThat(data.isDeltaPropagation()).isEqualTo(config.getDeltaPropagation());
+    assertThat(data.getRedundancyZone()).isEqualTo(config.getRedundancyZone());
+    assertThat(data.isEnforceUniqueHost()).isEqualTo(config.getEnforceUniqueHost());
+    assertThat(data.getStatisticSampleRate()).isEqualTo(config.getStatisticSampleRate());
   }
 
   private static String removeVMDir(String string) {
     return string.replaceAll("vm.", "");
   }
 
-  public static void startManager() {
-    MemberMXBean bean = getManagementService().getMemberMXBean();
-    // When the cache is created if jmx-manager is true then we create the manager.
-    // So it may already exist when we get here.
-    if (!bean.isManagerCreated()) {
-      if (!bean.createManager()) {
-        fail("Could not create Manager");
-      } else if (!bean.isManagerCreated()) {
-        fail("Should have been a manager after createManager returned true.");
-      }
-    }
-    ManagerMXBean mngrBean = getManagementService().getManagerMXBean();
-    try {
-      mngrBean.start();
-    } catch (JMException e) {
-      fail("Could not start Manager " + e);
+  private void startManager() throws JMException {
+    ManagementService service = this.managementTestRule.getManagementService();
+    MemberMXBean memberMXBean = service.getMemberMXBean();
+    if (memberMXBean.isManagerCreated()) {
+      return;
     }
-    assertTrue(mngrBean.isRunning());
-    assertTrue(getManagementService().isManager());
-    assertTrue(bean.isManager());
-  }
-
-  public static void isManager() {
-    MemberMXBean bean = getManagementService().getMemberMXBean();
-    if (bean.createManager()) {
-      ManagerMXBean mngrBean = getManagementService().getManagerMXBean();
-      try {
-        mngrBean.start();
-      } catch (JMException e) {
-        fail("Could not start Manager " + e);
-      }
-    } else {
-      fail(" Could not create Manager");
-    }
-  }
 
-  public static String fetchLog() {
-    MemberMXBean bean = getManagementService().getMemberMXBean();
-    String log = bean.showLog(30);
-    return log;
-  }
+    // TODO: cleanup this mess
+    // When the cache is created if jmx-managerVM is true then we create the managerVM.
+    // So it may already exist when we get here.
 
-  public static void fetchJVMMetrics() {
-    MemberMXBean bean = getManagementService().getMemberMXBean();
-    JVMMetrics metrics = bean.showJVMMetrics();
+    assertThat(memberMXBean.createManager()).isTrue();
+    assertThat(memberMXBean.isManagerCreated()).isTrue();
 
-    LogWriterUtils.getLogWriter()
-        .info("<ExpectedString> JVMMetrics is " + metrics.toString() + "</ExpectedString> ");
-  }
+    ManagerMXBean managerMXBean = service.getManagerMXBean();
+    managerMXBean.start();
 
-  public static void fetchOSMetrics() {
-    MemberMXBean bean = getManagementService().getMemberMXBean();
-    OSMetrics metrics = bean.showOSMetrics();
+    assertThat(managerMXBean.isRunning()).isTrue();
+    assertThat(memberMXBean.isManager()).isTrue();
+    assertThat(service.isManager()).isTrue();
+  }
 
-    LogWriterUtils.getLogWriter()
-        .info("<ExpectedString> OSMetrics is " + metrics.toString() + "</ExpectedString> ");
+  private String fetchLog(final int numberOfLines) {
+    ManagementService service = this.managementTestRule.getManagementService();
+    MemberMXBean memberMXBean = service.getMemberMXBean();
+    return memberMXBean.showLog(numberOfLines);
   }
 
-  public static void shutDownMember() {
-    MemberMXBean bean = getManagementService().getMemberMXBean();
-    bean.shutDownMember();
+  private JVMMetrics fetchJVMMetrics() {
+    ManagementService service = this.managementTestRule.getManagementService();
+    MemberMXBean memberMXBean = service.getMemberMXBean();
+    JVMMetrics metrics = memberMXBean.showJVMMetrics();
+    return metrics;
   }
 
-  public static void assertExpectedMembers(int expectedMemberCount) {
-    Wait.waitForCriterion(new WaitCriterion() {
-      public String description() {
-        return "Waiting all nodes to shutDown";
-      }
+  private OSMetrics fetchOSMetrics() {
+    ManagementService service = this.managementTestRule.getManagementService();
+    MemberMXBean memberMXBean = service.getMemberMXBean();
+    OSMetrics metrics = memberMXBean.showOSMetrics();
+    return metrics;
+  }
 
-      public boolean done() {
-        GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-        Set<DistributedMember> setOfOtherMembers =
-            cache.getDistributedSystem().getAllOtherMembers();
-        boolean done = (setOfOtherMembers != null && setOfOtherMembers.size() == 1);
-        return done;
-      }
+  private void shutDownMember() {
+    ManagementService service = this.managementTestRule.getManagementService();
+    MemberMXBean memberMXBean = service.getMemberMXBean();
+    memberMXBean.shutDownMember();
+  }
 
-    }, MAX_WAIT, 500, true);
+  private void verifyExpectedMembers(final int otherMembersCount) {
+    String alias = "awaiting " + this.managementTestRule.getOtherNormalMembers() + " to have size "
+        + otherMembersCount;
+    await(alias).until(() -> assertThat(this.managementTestRule.getOtherNormalMembers())
+        .hasSize(otherMembersCount));
   }
 
-  public static void invokeRemoteOps() throws Exception {
-    GemFireCacheImpl cache = GemFireCacheImpl.getInstance();
-    Set<DistributedMember> otherMemberSet =
-        cache.getDistributionManager().getOtherNormalDistributionManagerIds();
+  private void invokeRemoteMemberMXBeanOps() throws Exception {
+    Set<DistributedMember> otherMembers = this.managementTestRule.getOtherNormalMembers();
+
+    for (DistributedMember member : otherMembers) {
+      MemberMXBean memberMXBean = awaitMemberMXBeanProxy(member);
 
-    for (DistributedMember member : otherMemberSet) {
-      MemberMXBean bean = MBeanUtil.getMemberMbeanProxy(member);
-      JVMMetrics metrics = bean.showJVMMetrics();
+      JVMMetrics metrics = memberMXBean.showJVMMetrics();
 
-      LogWriterUtils.getLogWriter()
-          .info("<ExpectedString> JVMMetrics is " + metrics.toString() + "</ExpectedString> ");
-      LogWriterUtils.getLogWriter()
-          .info("<ExpectedString> OSMetrics is " + metrics.toString() + "</ExpectedString> ");
+      String value = metrics.toString();
+      boolean isManager = memberMXBean.isManager();
 
-      LogWriterUtils.getLogWriter()
-          .info("<ExpectedString> Boolean Data Check " + bean.isManager() + "</ExpectedString> ");
+      // TODO: need assertions
+
+      // ("<ExpectedString> JVMMetrics is " + metrics.toString() + "</ExpectedString> ");
+      // ("<ExpectedString> OSMetrics is " + metrics.toString() + "</ExpectedString> ");
+      // ("<ExpectedString> Boolean Data Check " + bean.isManager() + "</ExpectedString> ");
     }
   }
 
-  @Test
-  public void testNotification() throws Exception {
-    List<VM> managedNodeList = getManagedNodeList();
-    VM node1 = managedNodeList.get(0);
-    VM node2 = managedNodeList.get(1);
-    VM node3 = managedNodeList.get(2);
-    VM managingNode = getManagingNode();
+  private void attachListenerToDistributedSystemMXBean(final VM managerVM) {
+    managerVM.invoke("attachListenerToDistributedSystemMXBean", () -> {
+      ManagementService service = this.managementTestRule.getManagementService();
+      assertThat(service.isManager()).isTrue();
 
-    // Step : 1 : Create Managed Node Caches
-    createCache(node1);
-    createCache(node2);
-    createCache(node3);
-
-    // Step : 2 : Create Managing Node Cache, start manager, add a notification
-    // handler to DistributedSystemMXBean
-    createManagementCache(managingNode);
-    startManagingNode(managingNode);
-    attchListenerToDSMBean(managingNode);
+      NotificationListener listener = (final Notification notification, final Object handback) -> {
+        if (notification.getType().equals(JMXNotificationType.REGION_CREATED)) {
+          notifications.add(notification);
+        }
+      };
 
-    // Step : 3 : Verify Notification count, notification region sizes
-    countNotificationsAndCheckRegionSize(node1, node2, node3, managingNode);
+      ManagementFactory.getPlatformMBeanServer().addNotificationListener(
+          MBeanJMXAdapter.getDistributedSystemName(), listener, null, null);
+    });
   }
 
-  @Test
-  public void testNotificationManagingNodeFirst() throws Exception {
-    List<VM> managedNodeList = getManagedNodeList();
-    VM node1 = managedNodeList.get(0);
-    VM node2 = managedNodeList.get(1);
-    VM node3 = managedNodeList.get(2);
-    VM managingNode = getManagingNode();
+  private void verifyNotificationsAndRegionSize(final VM memberVM1, final VM memberVM2,
+      final VM memberVM3, final VM managerVM) {
+    DistributedMember member1 = this.managementTestRule.getDistributedMember(memberVM1);
+    DistributedMember member2 = this.managementTestRule.getDistributedMember(memberVM2);
+    DistributedMember member3 = this.managementTestRule.getDistributedMember(memberVM3);
 
-    // Step : 1 : Create Managing Node Cache, start manager, add a notification
-    // handler to DistributedSystemMXBean
-    createManagementCache(managingNode);
-    startManagingNode(managingNode);
-    attchListenerToDSMBean(managingNode);
+    String memberId1 = MBeanJMXAdapter.getUniqueIDForMember(member1);
+    String memberId2 = MBeanJMXAdapter.getUniqueIDForMember(member2);
+    String memberId3 = MBeanJMXAdapter.getUniqueIDForMember(member3);
 
-    // Step : 2 : Create Managed Node Caches
-    createCache(node1);
-    createCache(node2);
-    createCache(node3);
+    memberVM1.invoke("createNotificationRegion", () -> createNotificationRegion(memberId1));
+    memberVM2.invoke("createNotificationRegion", () -> createNotificationRegion(memberId2));
+    memberVM3.invoke("createNotificationRegion", () -> createNotificationRegion(memberId3));
 
-    // Step : 3 : Verify Notification count, notification region sizes
-    countNotificationsAndCheckRegionSize(node1, node2, node3, managingNode);
-  }
+    managerVM.invoke("verify notifications size", () -> {
+      await().until(() -> assertThat(notifications.size()).isEqualTo(45));
 
-  @Test
-  public void testRedundancyZone() throws Exception {
-    List<VM> managedNodeList = getManagedNodeList();
-    VM node1 = managedNodeList.get(0);
-    VM node2 = managedNodeList.get(1);
-    VM node3 = managedNodeList.get(2);
-    Properties props = new Properties();
-    props.setProperty(REDUNDANCY_ZONE, "ARMY_ZONE");
+      Cache cache = this.managementTestRule.getCache();
 
-    createCache(node1, props);
+      Region region1 = cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + memberId1);
+      Region region2 = cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + memberId2);
+      Region region3 = cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + memberId3);
 
-    node1.invoke(new SerializableRunnable("Assert Redundancy Zone") {
+      // Even though we got 15 notification only 10 should be there due to
+      // eviction attributes set in notification region
 
-      public void run() {
-        ManagementService service = ManagementService.getExistingManagementService(getCache());
-        MemberMXBean bean = service.getMemberMXBean();
-        assertEquals("ARMY_ZONE", bean.getRedundancyZone());
-      }
+      await().until(() -> assertThat(region1).hasSize(10));
+      await().until(() -> assertThat(region2).hasSize(10));
+      await().until(() -> assertThat(region3).hasSize(10));
     });
   }
 
-  protected void attchListenerToDSMBean(final VM vm) {
-    SerializableRunnable attchListenerToDSMBean =
-        new SerializableRunnable("Attach Listener to DS MBean") {
-          public void run() {
-            assertTrue(managementService.isManager());
-            DistributedSystemMXBean dsMBean = managementService.getDistributedSystemMXBean();
-
-            // First clear the notification list
-            notifList.clear();
-
-            NotificationListener nt = new NotificationListener() {
-              @Override
-              public void handleNotification(Notification notification, Object handback) {
-                if (notification.getType().equals(JMXNotificationType.REGION_CREATED)) {
-                  notifList.add(notification);
-                }
-              }
-            };
-
-            try {
-              mbeanServer.addNotificationListener(MBeanJMXAdapter.getDistributedSystemName(), nt,
-                  null, null);
-            } catch (InstanceNotFoundException e) {
-              throw new AssertionError("Failed With Exception ", e);
-            }
-
-          }
-        };
-    vm.invoke(attchListenerToDSMBean);
-  }
-
-  public void waitForManagerToRegisterListener() {
-    SystemManagementService service = (SystemManagementService) getManagementService();
-    final Map<ObjectName, NotificationHubListener> hubMap =
+  private void createNotificationRegion(final String memberId) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    Map<ObjectName, NotificationHubListener> notificationHubListenerMap =
         service.getNotificationHub().getListenerObjectMap();
 
-    Wait.waitForCriterion(new WaitCriterion() {
-      public String description() {
-        return "Waiting for manager to register the listener";
-      }
+    await().until(() -> assertThat(notificationHubListenerMap.size()).isEqualTo(1));
 
-      public boolean done() {
-        boolean done = (1 == hubMap.size());
-        return done;
-      }
+    RegionFactory regionFactory =
+        this.managementTestRule.getCache().createRegionFactory(RegionShortcut.REPLICATE);
+    for (int i = 1; i <= 15; i++) {
+      regionFactory.create(NOTIFICATION_REGION_NAME + i);
+    }
+    Region region = this.managementTestRule.getCache()
+        .getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + memberId);
 
-    }, MAX_WAIT, 500, true);
+    assertThat(region).isEmpty();
   }
 
-  public void countNotificationsAndCheckRegionSize(VM node1, VM node2, VM node3, VM managingNode) {
-
-    DistributedMember member1 = getMember(node1);
-    DistributedMember member2 = getMember(node2);
-    DistributedMember member3 = getMember(node3);
-
-    final String appender1 = MBeanJMXAdapter.getUniqueIDForMember(member1);
-    final String appender2 = MBeanJMXAdapter.getUniqueIDForMember(member2);
-    final String appender3 = MBeanJMXAdapter.getUniqueIDForMember(member3);
-
-    node1.invoke("Create Regions", () -> createNotifTestRegion(appender1));
-    node2.invoke("Create Regions", () -> createNotifTestRegion(appender2));
-    node3.invoke("Create Regions", () -> createNotifTestRegion(appender3));
+  private MemberMXBean awaitMemberMXBeanProxy(final DistributedMember member) {
+    SystemManagementService service = this.managementTestRule.getSystemManagementService();
+    ObjectName objectName = service.getMemberMBeanName(member);
 
-    managingNode.invoke(new SerializableRunnable("Validate Notification Count") {
-
-      public void run() {
-
-        Wait.waitForCriterion(new WaitCriterion() {
-          public String description() {
-            return "Waiting for all the RegionCreated notification to reach the manager "
-                + notifList.size();
-          }
-
-          public boolean done() {
-            boolean done = (45 == notifList.size());
-            return done;
-          }
-
-        }, MAX_WAIT, 500, true);
-
-        assertEquals(45, notifList.size());
-        Cache cache = getCache();
-        SystemManagementService service = (SystemManagementService) getManagementService();
-
-        Region member1NotifRegion =
-            cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + appender1);
-        Region member2NotifRegion =
-            cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + appender2);
-        Region member3NotifRegion =
-            cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + appender3);
-
-        // Even though we got 15 notification only 10 should be there due to
-        // eviction attributes set in notification region
-
-        waitAtMost(5, TimeUnit.SECONDS).untilCall(to(member1NotifRegion).size(), equalTo(10));
-        waitAtMost(5, TimeUnit.SECONDS).untilCall(to(member2NotifRegion).size(), equalTo(10));
-        waitAtMost(5, TimeUnit.SECONDS).untilCall(to(member3NotifRegion).size(), equalTo(10));
-      }
-    });
+    String alias = "awaiting MemberMXBean proxy for " + member;
+    await(alias)
+        .until(() -> assertThat(service.getMBeanProxy(objectName, MemberMXBean.class)).isNotNull());
 
+    return service.getMBeanProxy(objectName, MemberMXBean.class);
   }
 
-  private void createNotifTestRegion(final String appender1) {
-    Cache cache = getCache();
-
-    waitForManagerToRegisterListener();
-    RegionFactory rf = cache.createRegionFactory(RegionShortcut.REPLICATE);
-    for (int i = 1; i <= 15; i++) {
-      rf.create("NotifTestRegion_" + i);
-    }
-    Region member1NotifRegion =
-        cache.getRegion(ManagementConstants.NOTIFICATION_REGION + "_" + appender1);
-
-    assertEquals(0, member1NotifRegion.size());
+  private ConditionFactory await() {
+    return Awaitility.await().atMost(2, MINUTES);
   }
 
+  private ConditionFactory await(final String alias) {
+    return Awaitility.await(alias).atMost(2, MINUTES);
+  }
 }