@Test
    public void testLeaveGroupEpoch() {
        // Static member should leave the group with epoch -2.
        MembershipManagerImpl membershipManager = createMemberInStableState("instance1");
        mockLeaveGroup();
        membershipManager.leaveGroup();
        verify(subscriptionState).unsubscribe();
        assertEquals(MemberState.LEAVING, membershipManager.state());
        assertEquals(ConsumerGroupHeartbeatRequest.LEAVE_GROUP_STATIC_MEMBER_EPOCH,
                membershipManager.memberEpoch());

        // Dynamic member should leave the group with epoch -1.
        membershipManager = createMemberInStableState(null);
        mockLeaveGroup();
        membershipManager.leaveGroup();
        verify(subscriptionState).unsubscribe();
        assertEquals(MemberState.LEAVING, membershipManager.state());
        assertEquals(ConsumerGroupHeartbeatRequest.LEAVE_GROUP_MEMBER_EPOCH,
                membershipManager.memberEpoch());
    }
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