@Test
  public void testResolvePortConflict() throws Exception {
    // raises port conflict between 1st call and 2nd call of randomPort() by mocking Random object
    Random random = mock(Random.class);
    when(random.nextInt(anyInt())).thenAnswer(new Answer<Integer>() {
      int[] numbers = { 1, 1, 2 };
      int count = 0;

      @Override
      public Integer answer(InvocationOnMock invocation) {
        int ret = numbers[count];
        count++;
        return ret;
      }
    });

    HBaseTestingUtil.PortAllocator.AvailablePortChecker portChecker =
      mock(HBaseTestingUtil.PortAllocator.AvailablePortChecker.class);
    when(portChecker.available(anyInt())).thenReturn(true);

    HBaseTestingUtil.PortAllocator portAllocator =
      new HBaseTestingUtil.PortAllocator(random, portChecker);

    int port1 = portAllocator.randomFreePort();
    int port2 = portAllocator.randomFreePort();
    assertNotEquals(port1, port2);
    Mockito.verify(random, Mockito.times(3)).nextInt(anyInt());
  }
Test that we can start and stop multiple time a cluster with the same HBaseTestingUtility.
hbase-server/src/test/java/org/apache/hadoop/hbase/TestHBaseTestingUtil.java