@Test
  public void
      sendMessageWithAutomaticFunctionCallingResponderFinishReasonNotStop_chatHistoryGetReverted()
          throws IOException, NoSuchMethodException {
    // (Arrange) Set up the return value of the generateContent
    when(mockGenerativeModel.generateContent(
            Arrays.asList(ContentMaker.fromString(FUNCTION_CALL_MESSAGE))))
        .thenReturn(RESPONSE_WITH_FUNCTION_CALL);
    when(mockGenerativeModel.generateContent(
            Arrays.asList(
                ContentMaker.fromString(FUNCTION_CALL_MESSAGE),
                ResponseHandler.getContent(RESPONSE_WITH_FUNCTION_CALL),
                FUNCTION_RESPONSE_CONTENT)))
        .thenReturn(RESPONSE_FROM_UNARY_CALL_WITH_OTHER_FINISH_REASON);

    // (Act) Send text message via sendMessage
    AutomaticFunctionCallingResponder responder = new AutomaticFunctionCallingResponder();
    responder.addCallableFunction(
        FUNCTION_CALL_NAME,
        ChatSessionTest.class.getMethod(FUNCTION_CALL_NAME, String.class),
        FUNCTION_CALL_PARAMETER_NAME);
    GenerateContentResponse response =
        chat.withAutomaticFunctionCallingResponder(responder).sendMessage(FUNCTION_CALL_MESSAGE);

    // (Act & Assert) get history will throw since the final response stopped with error. The
    // history should be reverted.
    assertThat(response).isEqualTo(RESPONSE_FROM_UNARY_CALL_WITH_OTHER_FINISH_REASON);
    IllegalStateException thrown =
        assertThrows(IllegalStateException.class, () -> chat.getHistory());
    assertThat(thrown).hasMessageThat().isEqualTo("Rerun getHistory() to get cleaned history.");
    // Assert that the history can be fetched again and it's empty.
    List<Content> history = chat.getHistory();
    assertThat(history.size()).isEqualTo(0);
  }
Callable function getCurrentWeather for testing automatic function calling.
java-vertexai/google-cloud-vertexai/src/test/java/com/google/cloud/vertexai/generativeai/ChatSessionTest.java