@Test
    public void testFencingWhenStateIsLeaving() {
        MembershipManagerImpl membershipManager = createMemberInStableState();

        // Start leaving group.
        mockLeaveGroup();
        CompletableFuture<Void> leaveOperation = membershipManager.leaveGroup();
        verify(subscriptionState).unsubscribe();
        assertEquals(MemberState.LEAVING, membershipManager.state());

        // Get fenced while leaving. Member should not trigger any callback or try to
        // rejoin, and should continue leaving the group as it was before getting fenced.
        clearInvocations(subscriptionState);
        membershipManager.transitionToFenced();
        testFenceIsNoOp(membershipManager);
        assertEquals(MemberState.UNSUBSCRIBED, membershipManager.state(), "Member should " +
            "transition from LEAVING to UNSUBSCRIBED when getting fenced (it does not need to " +
            "send leave request if fenced");
        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