The original question can be found here. However, as an overview, the code is responsible for assigning Leads to sales representatives with round-robin distribution based on the Queue that is assigned via Flow Builder.

When testing the following scenario, my assert fails. The test allows me to ensure Leads are not being assigned to users who are not members of the queue.

Scenario: 2 Queues + 2 Users + 2 Leads (1 assigned to Queue 2 and 1 assigned to Queue 2)

Question: I expect the testLead with Company = 'TestAssignmentLead' to be assigned to a user who is a member of Queue1 (and vice versa) and that is not happening. What is wrong with the APEX Class (or Unit Test) that is causing my assert to fail? The error I receive is: 'Expected: TestGroupOneUser, Actual: TestGroupTwoUser'

Below you will find the class as well as the unit test.

APEX Class: LeadAssignment

public with sharing class LeadAssignment{
// -------- Variables --------
// Lead Assignment prep
private static Set<Id> queueIds = new Set<Id>(), leadIds = new Set<Id>(), userIds = new Set<Id>();

// Lead Updated Records
private static Lead[] updatedRecords = new Lead[0];

// Group Members
private static Map<Id, Id[]> queueUsers = new Map<Id, Id[]>();

// Group Mebmers based on Lead ID 
private static Set<Id> leadQueueUsers = new Set<Id>();

// Exceptions for Error Handling
private static List<Exception__c> createExceptions = new List<Exception__c>();

public static List<AssignLeadActionResult> assignLeads(List<AssignLeadActionRequest> requests){ 
    List<AssignLeadActionResult> results = new List<AssignLeadActionResult>();
    //Set<Id> queueIds = new Set<Id>(), leadIds = new Set<Id>(), userIds = new Set<Id>();
    //Lead[] updatedRecords = new Lead[0];
    //Map<Id, Id[]> queueUsers = new Map<Id, Id[]>();

    // --- AGGREGATE DATA PHASE --- //
    // Get all queue Ids and lead Ids.
    for(AssignLeadActionRequest request: requests) {
    // Initialize queue->user Map
    for(Id queueId: queueIDs) {
        queueUsers.put(queueId, new Id[0]);

    // --- QUERY DATA PHASE --- //
    // Get all leads present
    Map<Id, Lead> leads = new Map<Id, Lead>([SELECT Id, OwnerId, Lead_Round_Robin__c FROM Lead WHERE Id = :leadIds]);
    // Get all queue members
    for(GroupMember member: [SELECT UserOrGroupId, GroupId FROM GroupMember WHERE GroupId = :queueIds]) {
        if(member.UserOrGroupId.getSObjectType() == User.sobjectType) {
    // Eliminate inactive users
    for(User record: [SELECT Id FROM User WHERE IsActive = false AND Id = :userIds]) {

    System.debug('This is userIds:' + userIds);

    // --- UPDATE DATA PHASE --- //
    // Rebuild Queue users
    for(Id queueId: queueUsers.keySet()) {
        Id[] tempUserIds = queueUsers.get(queueId);
        Set<Id> activeUsers = new Set<Id>(tempUserIds);

    // For each request, figure out possible assignees
    for(AssignLeadActionRequest request: requests) {
        //Set<Id> leadQueueUsers = new Set<Id>();
        for(Id queueId: request.queueIds) {
        Id[] repAssignList = new List<Id>(leadQueueUsers);
        repAssignList.sort(); // For consistency
        // For each lead, assign active user
        for(Id leadRecord: request.leadIds) {
            Lead tempLead = leads.remove(leadRecord);
            if(tempLead != null) {
                if(repAssignList.isEmpty()) {

                    createExceptions.add(EvolveException.buildException('LeadAssignment', 'assignLead', 'No possible assignments'));
                    System.debug('assignLead: ' + 'No possible assignments'); 

                    insert createExceptions; 

                } else {
                    tempLead.OwnerId = repAssignList[Math.mod(Integer.valueOf(tempLead.Lead_Round_Robin__c), repAssignList.size())];

            } else {
                // Oops, duplicate lead in same transaction, report error.
                createExceptions.add(EvolveException.buildException('LeadAssignment', 'assignLead', 'duplicate lead in same transaction'));
                System.debug('assignLead: ' + 'Duplicate lead in same transaction'); 

                insert createExceptions;
    update updatedRecords;

    return results;

public class AssignLeadActionRequest {
    @InvocableVariable(required = false)
    public List<ID> queueIDs;

    @InvocableVariable(required = false)
    public List<Id> leadIDs;

public class AssignLeadActionResult {
    @InvocableVariable(required = false)
    public List<Id> leadIDs;


The APEX Test Class:

private class leadRoundRobinAssignment_Test 
        // -------- Variables --------
        // Records
        private static List<User> testUsers = new List<User>();
        private static List<Lead> testLeads = new List<Lead>();
        private static List<Group> testGroups = new List<Group>();
        private static List<QueueSObject> testQueues = new List<QueueSObject>();
        private static List<GroupMember> testGroupMembers = new List<GroupMember>();

        // -------- Set Ups --------
        // Test data prep

        private static void initTestData(Integer testType)
            if(testType == 0)
            testUsers.add(UnitTestFactory.testUser('testLeadAssignment0@noemail.com', 'TestLastSystemAdmin0', 'System Administrator'));
            testUsers.add(UnitTestFactory.testUser('testLeadAssignment1@noemail.com', 'TestLastGroupOneUser1', 'EVRN Regional Director User'));
            testUsers.add(UnitTestFactory.testUser('testLeadAssignment2@noemail.com', 'TestLastGroupOneUser2', 'EVRN Regional Director User'));
            testUsers.add(UnitTestFactory.testUser('testLeadAssignment3@noemail.com', 'TestLastGroupTwoUser1', 'EVRN Regional Director User'));
            testUsers[1].FirstName = 'TestGroupOneUser';
            testUsers[2].FirstName = 'TestGroupOneUser';
            testUsers[3].FirstName = 'TestGroupTwoUser';
            insert testUsers;   

            testGroups.add(testGroup('QueueAssignmentOne', 'QueueAssignmentOneDN', 'Queue'));
            testGroups.add(testGroup('QueueAssignmentTwo', 'QueueAssignmentTwoDN', 'Queue'));
            insert testGroups;  

            testQueues.add(testQueue(testGroups[0].ID, 'Lead'));
            testQueues.add(testQueue(testGroups[1].ID, 'Lead'));
            insert testQueues;     

            testGroupMembers.add(testGroupMember(testGroups[0].ID, testUsers[1].ID));
            testGroupMembers.add(testGroupMember(testGroups[0].ID, testUsers[2].ID));
            testGroupMembers.add(testGroupMember(testGroups[1].ID, testUsers[3].ID));
            insert testGroupMembers;               


    private static Group testGroup(String name, String developerName, String groupType)
        Group result = new Group();
        result.Name = name;
        result.DeveloperName = developerName;
        result.Type = groupType;

        return result;

    private static QueueSObject testQueue(ID groupID, String sObjectType)
        QueueSObject result = new QueueSObject();
        result.QueueID = groupID;
        result.SObjectType = sObjectType;

        return result;
    private static GroupMember testGroupMember(ID groupID, ID UserOrGroupId)
        GroupMember result = new GroupMember();
        result.GroupId = groupID;
        result.UserOrGroupId = UserOrGroupId;

        return result;

    private static void testTwoQueuesTwoUsersLeadReassignment() 




            testLeads.add(UnitTestFactory.testLead(RecordTypeHelper.getRecordType('Lead', 'Home Owner').ID, 'TestAssignmentLead'));
            testLeads.add(UnitTestFactory.testLead(RecordTypeHelper.getRecordType('Lead', 'Home Owner').ID, 'TestAssignmentLead1'));
            testLeads[0].Company = 'TestAssignmentLead';
            testLeads[0].OwnerID = testGroups[0].ID;
            testLeads[1].Company = 'TestAssignmentLead1';
            testLeads[1].OwnerID = testGroups[1].ID;
            insert testLeads;

            LeadAssignment.AssignLeadActionRequest request = new LeadAssignment.AssignLeadActionRequest();
            request.queueIDs = new List<Id>{testGroups[0].ID, testGroups[1].ID}; 
            //request.leadID = new List<Id>{testLeads[0].ID, testLeads[1].ID};
            request.leadIDs = new List<Id>{testLeads[0].ID, testLeads[1].ID};

            List<LeadAssignment.AssignLeadActionRequest> requests = new List<LeadAssignment.AssignLeadActionRequest>();

            List<LeadAssignment.AssignLeadActionResult> results = LeadAssignment.assignLeads(requests);



        List<Lead> leadList = [SELECT ID, OwnerID, Company, Owner_First_Name__c, LastName FROM Lead WHERE LastName LIKE 'TestAssignmentLead%' order by CreatedDate desc];
        System.Debug('leadList: ' + leadList); 

        for (Lead singleLead : leadList)
            if(singleLead.Company == 'TestAssignmentLead')
                System.assertEquals('TestGroupOneUser', singleLead.Owner_First_Name__c);
            else if(singleLead.Company == 'TestAssignmentLead1') 
                // System.assertEquals('TestGroupTwoUser', singleLead.Owner_First_Name__c);

        //System.assertEquals(testUsers[1].ID, leadList[0].OwnerID);
        //System.assertEquals(testUsers[3].ID, leadList[1].OwnerID);
  • 3
    What is your question? – Sebastian Kessel May 15 at 22:01
  • 2
    Your question is almost good. You need to explain what you're expecting, and what you actually get from the unit test. Once we have this, we'll be better equipped to help you. – sfdcfox May 16 at 4:26
  • I added the question to the body of the description. I assumed the question was implied if the test class fails at the assert in the unit test. – Larry Caper May 16 at 14:06
  • Hi Larry, please take a moment to scroll through the tour and read How to Ask. The format here is specific questions and answers. A good question post will always ask something explicit. What seems obvious to you may not be so to others, and there should not be any guesswork as to what you actually want to ask (but didn't, in this case). – Adrian Larson May 18 at 19:22
  • Is the question (i.e., where it says "Question:") within the description not specific enough? – Larry Caper May 20 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.