@Test
  public void
      sendMessageWithAutomaticFunctionCallingResponderIllegalStateException_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_WITH_FUNCTION_CALL);
    when(mockGenerativeModel.generateContent(
            Arrays.asList(
                ContentMaker.fromString(FUNCTION_CALL_MESSAGE),
                ResponseHandler.getContent(RESPONSE_WITH_FUNCTION_CALL),
                FUNCTION_RESPONSE_CONTENT,
                ResponseHandler.getContent(RESPONSE_WITH_FUNCTION_CALL),
                FUNCTION_RESPONSE_CONTENT)))
        .thenReturn(RESPONSE_FROM_UNARY_CALL);

    // (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);

    // After mocking, there should be 2 consecutive auto function calls, but the max number of
    // function calls in the responder is 1, so an IllegalStateException will be thrown.
    IllegalStateException thrown =
        assertThrows(
            IllegalStateException.class,
            () ->
                chat.withAutomaticFunctionCallingResponder(responder)
                    .sendMessage(FUNCTION_CALL_MESSAGE));
    assertThat(thrown)
        .hasMessageThat()
        .contains("Exceeded the maximum number of continuous automatic function calls");

    // (Act & Assert) get history and assert that the history contains no contents since the
    // intermediate response got an error and all contents got reverted.
    assertThat(chat.getHistory().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