@Test
    public void testFencingWhenStateIsPrepareLeavingCompletesTheLeaveOperation() {
        MembershipManagerImpl membershipManager = createMemberInStableState();
        mockPrepareLeaving(new TopicPartition("topic1", 0));
        CompletableFuture<Void> leaveOperation = membershipManager.leaveGroup();
        assertEquals(MemberState.PREPARE_LEAVING, membershipManager.state());
        assertFalse(leaveOperation.isDone());
        clearInvocations(subscriptionState);

        membershipManager.transitionToFenced();

        testFenceIsNoOp(membershipManager);
        assertEquals(MemberState.UNSUBSCRIBED, membershipManager.state());
        assertTrue(leaveOperation.isDone(), "Fenced member should complete the ongoing leave operation");
    }
Members keep sending heartbeats while preparing to leave, so they could get fenced. This
tests ensures that if a member gets fenced while preparing to leave, it will directly
transition to UNSUBSCRIBE (no callbacks triggered or rejoin as in regular fencing
scenarios), and when the PREPARE_LEAVING completes it remains UNSUBSCRIBED (no last
heartbeat sent).
clients/src/test/java/org/apache/kafka/clients/consumer/internals/MembershipManagerImplTest.java