@Test
  public void testLeakOperationHandle() throws HiveSQLException {
    //create HiveSessionImpl object
    TProtocolVersion protocol = TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V2;
    String username = "";
    String password = "";
    HiveConf serverhiveConf = new HiveConf();
    String ipAddress = null;
    HiveSessionImpl session = new HiveSessionImpl(null, protocol, username, password,
      serverhiveConf, ipAddress, null) {
      @Override
      protected synchronized void acquire(boolean userAccess, boolean isOperation) {
      }

      @Override
      protected synchronized void release(boolean userAccess, boolean isOperation) {
      }
    };

    //mock operationManager for session
    OperationManager operationManager = Mockito.mock(OperationManager.class);
    session.setOperationManager(operationManager);

    //mock operation and opHandle for operationManager
    ExecuteStatementOperation operation = Mockito.mock(ExecuteStatementOperation.class);
    OperationHandle opHandle = Mockito.mock(OperationHandle.class);
    Mockito.when(operation.getHandle()).thenReturn(opHandle);
    Map<String, String> confOverlay = new HashMap<String, String>();
    String hql = "drop table if exists table_not_exists";
    Mockito.when(operationManager.newExecuteStatementOperation(same(session), eq(hql),
        (Map<String, String>)Mockito.any(), eq(true), eq(0L))).thenReturn(operation);

    try {

      //Running a normal async query with no exceptions,then no need to close opHandle
      session.open(new HashMap<String, String>());
      session.executeStatementAsync(hql, confOverlay);
      Mockito.verify(operationManager, Mockito.times(0)).closeOperation(opHandle);

      // Throw an HiveSqlException when do async calls
      Mockito.doThrow(new HiveSQLException("Fail for clean up test")).when(operation).run();
      session.executeStatementAsync(hql, confOverlay);
      Assert.fail("HiveSqlException expected.");

    } catch (HiveSQLException e) {
      if (!"Fail for clean up test".equals(e.getMessage())) {
        Assert.fail("unexpected exception:" + Arrays.toString(e.getStackTrace()));
      }
      //operationManager.closeOperation() is expected to be invoked once
      Mockito.verify(operationManager, Mockito.times(1)).closeOperation(opHandle);
    }
  }
Verifying OperationManager.closeOperation(opHandle) is invoked when
get HiveSQLException during sync query
@throws HiveSQLException
itests/hive-unit/src/test/java/org/apache/hive/service/cli/session/TestHiveSessionImpl.java