IGNITE-15069 Fix flaky GridCommandHandlerTest.testSetState - Fixes #9252.

Signed-off-by: Ivan Daschinsky <ivandasch@apache.org>
diff --git a/modules/control-utility/src/test/java/org/apache/ignite/util/GridCommandHandlerTest.java b/modules/control-utility/src/test/java/org/apache/ignite/util/GridCommandHandlerTest.java
index 0b4ddf2..5551d11 100644
--- a/modules/control-utility/src/test/java/org/apache/ignite/util/GridCommandHandlerTest.java
+++ b/modules/control-utility/src/test/java/org/apache/ignite/util/GridCommandHandlerTest.java
@@ -103,6 +103,7 @@
 import org.apache.ignite.internal.processors.cache.warmup.BlockedWarmUpConfiguration;
 import org.apache.ignite.internal.processors.cache.warmup.BlockedWarmUpStrategy;
 import org.apache.ignite.internal.processors.cache.warmup.WarmUpTestPluginProvider;
+import org.apache.ignite.internal.processors.cluster.ChangeGlobalStateFinishMessage;
 import org.apache.ignite.internal.processors.cluster.GridClusterStateProcessor;
 import org.apache.ignite.internal.util.distributed.SingleNodeMessage;
 import org.apache.ignite.internal.util.future.IgniteFinishedFutureImpl;
@@ -495,7 +496,7 @@
 
     /**
      * Test verifies that persistence backup command to backup all caches backs up all cache directories.
-     * 
+     *
      * @throws Exception If failed.
      */
     @Test
@@ -963,11 +964,15 @@
     }
 
     /** */
-    private void setState(Ignite ignite, ClusterState state, String strState, String... cacheNames) {
+    private void setState(Ignite ignite, ClusterState state, String strState, String... cacheNames) throws Exception {
         log.info(ignite.cluster().state() + " -> " + state);
 
+        CountDownLatch latch = getNewStateLatch(ignite.cluster().state(), state);
+
         assertEquals(EXIT_CODE_OK, execute("--set-state", strState));
 
+        latch.await(getTestTimeout(), TimeUnit.MILLISECONDS);
+
         assertEquals(state, ignite.cluster().state());
 
         assertContains(log, testOut.toString(), "Cluster state changed to " + strState);
@@ -984,6 +989,22 @@
         }
     }
 
+   /** */
+   private CountDownLatch getNewStateLatch(ClusterState oldState, ClusterState newState) {
+        if (oldState != newState) {
+            CountDownLatch latch = new CountDownLatch(G.allGrids().size());
+
+            for (Ignite grid : G.allGrids()) {
+                ((IgniteEx)grid).context().discovery().setCustomEventListener(ChangeGlobalStateFinishMessage.class,
+                    ((topVer, snd, msg) -> latch.countDown()));
+            }
+
+            return latch;
+        }
+        else
+            return new CountDownLatch(0);
+   }
+
     /**
      * Test baseline collect works via control.sh
      *