@Test
    public void testFencingWhenStateIsLeaving() {
        ShareMembershipManager membershipManager = createMemberInStableState();
        mockPrepareLeaving(membershipManager);
        assertEquals(MemberState.LEAVING, membershipManager.state());

        // Get fenced while preparing to leave the group. Member should ignore the fence
        // (no rejoin) and should continue leaving the group as it was before getting fenced.
        clearInvocations(subscriptionState);
        membershipManager.transitionToFenced();
        testFenceIsNoOp(membershipManager);
        assertEquals(MemberState.LEAVING, membershipManager.state());

        membershipManager.onHeartbeatRequestSent();
        assertEquals(MemberState.UNSUBSCRIBED, membershipManager.state());

        // Last heartbeat sent is expected to fail, leading to a call to transitionToFenced. That
        // should be no-op because the member already left.
        clearInvocations(subscriptionState);
        membershipManager.transitionToFenced();
        testFenceIsNoOp(membershipManager);
        assertEquals(MemberState.UNSUBSCRIBED, membershipManager.state());
    }
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 (rejoin as in regular fencing scenarios), and when the
LEAVING completes it remains UNSUBSCRIBED (no last heartbeat sent).
clients/src/test/java/org/apache/kafka/clients/consumer/internals/ShareMembershipManagerTest.java