function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Greg-inficienceGreg-inficience 

Unit test for standard set controller extension

I am trying to write the test method for the following controller extension:

 

public class MassCreateLeadsFromContactsControllerExt {
    public string CampaignToAppendID;
    public list<contact> SelectedContacts;
    public boolean CampaignAlert = False;
    public boolean noContact = False;
    public boolean isContact = True;
    public boolean ProcessEnded = False;
    public integer ContactNumber =0;
    public integer ContactsProcessed = 0;

    public MassCreateLeadsFromContactsControllerExt(ApexPages.StandardSetController stdSetController) {
        list<contact> TheSelectedIDs;
        System.LoggingLevel level = LoggingLevel.FINEST;
//        system.debug ('Starting extension controller');
//        system.debug ('CampaignAlert: '+CampaignAlert);

        TheSelectedIDs = (list<Contact>)stdSetController.getselected();       
        if (TheSelectedIDs.size() > 0) {
            this.selectedcontacts = new list<Contact>();
            for (contact TheCurrentContact : TheSelectedIDs) {
                contact TheFullContact = ([SELECT id, name, firstname, lastname, title, accountid, email, phone, mobilephone, mailingcity, mailingcountry FROM contact where id = :TheCurrentContact.ID]);
                this.SelectedContacts.add(TheFullContact);
            }
//            system.debug ('SelectedContacts: '+this.SelectedContacts.size());
            this.contactnumber = this.SelectedContacts.size();
            this.noContact = False;
            this.isContact = True;
        } else {
            system.debug ('No Contact in list');
            this.ContactNumber = 0;
            this.noContact = True;
            this.isContact = False;
        }        
    }
    
    public pagereference CreateLeadsFromContacts() {
        Lead TheNewLead;
        Campaignmember TheNewCM;
        Campaignmember ContactCM;
        Contact TheFullContact;
        account TheAccount;
        
        if (CampaignToAppendID != '0') {
            Campaign TheCampaign = ([SELECT id, name FROM campaign where id = :CampaignToAppendID]);
//            system.debug ('Campaign to append: '+CampaignToAppendID+' - '+TheCampaign.name);
//            system.debug ('Nb of leads to create: '+SelectedContacts.size());

            for (contact TheCurrentContact : SelectedContacts) {
//                system.debug ('Contact to process: '+TheCurrentContact.ID);
                TheFullContact = ([SELECT id, firstname, lastname, salutation, title, accountid, email, phone, mobilephone, mailingstreet, mailingcity, mailingcountry, mailingpostalcode FROM contact where id = :TheCurrentContact.ID]);
                TheAccount = ([SELECT id, name, industry FROM account where id = :TheFullContact.accountid]);
                TheNewLead = new lead ();
                TheNewLead.firstname = TheFullContact.firstname;
                TheNewLead.lastname = TheFullContact.lastname;
                TheNewLead.title = TheFullContact.title;
                TheNewLead.Company = TheAccount.name;
                TheNewLead.email = TheFullContact.email;
                TheNewLead.phone = TheFullContact.phone;
                TheNewLead.mobilephone = TheFullContact.mobilephone;
                TheNewLead.industry = TheAccount.industry;
                TheNewLead.street = TheFullContact.mailingstreet;
                TheNewLead.city = TheFullContact.mailingcity;
                TheNewLead.country = TheFullContact.mailingcountry;
                TheNewLead.postalcode = TheFullContact.mailingpostalcode;
                TheNewLead.salutation = TheFullContact.salutation;
                
                try {
                    insert TheNewLead;
                    this.ContactsProcessed = this.ContactsProcessed +1;
                } catch (exception e) {
                }
//                system.debug ('New Lead insterted - ID: '+TheNewLead.ID);
                TheNewCM = new campaignMember();
                TheNewCM.leadid = TheNewLead.ID;
                TheNewCM.campaignid = TheCampaign.ID;
                try {
                    contactCM = ([SELECT contactid, status FROM campaignmember where campaignid = :TheCampaign.ID and contactid = :TheCurrentContact.id limit 1]);
                    if (contactCM != null) {
                        TheNewCM.status = contactCM.status;
                    } 
                } catch (exception e) {
//                    system.debug ('No campaign memeber status. default value will be used');
                }
                insert TheNewCM;
            }
//            system.debug('END OF PROCESSING');
            this.ProcessEnded = True;
            this.isContact = False;
            this.CampaignAlert = False;
            }
        else {
            this.CampaignAlert = True;
            system.debug('No campaign selected');
            }
        return null;
    }

    public List<SelectOption> getCampaignList() {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('0','-- No Campaign --'));
        for (campaign c : [SELECT id, name FROM campaign where isactive = TRUE order by name]) {
            options.add(new SelectOption(c.id,c.name));    
        }
//        system.debug('getCampaignsToAppend - Campaigns To Append drop list: '+options.size());
        return options;
    }

    public integer getContactNumber() {
        if (this.ContactNumber == null) {
            this.ContactNumber = 0;
        }
//        system.debug ('getContactNumber - ContactNumber: '+this.ContactNumber);
        return this.ContactNumber;
    }

    public integer getContactsProcessed() {
        if (this.ContactsProcessed == null) {
            this.ContactsProcessed = 0;
        }
//        system.debug ('getContactsProcessed - ContactsProcessed: '+this.ContactsProcessed);
        return this.ContactsProcessed;
    }

    public list<contact> getSelectedContacts() {
        if (This.SelectedContacts == null) {
            This.SelectedContacts = new List<contact>();
//            system.debug ('getSelectedContacts - found SelectedContacts null');
        }
//        system.debug ('getSelectedContacts - TheContacts: '+this.SelectedContacts.size());
        return This.SelectedContacts;
    }

    public string getCampaignToAppendID() {
        if(this.CampaignToAppendID == null) {
            this.CampaignToAppendID = '0';
        }
//        system.debug('getCampaignToAppend - CampaignToAppendID: '+this.CampaignToAppendID);
        return this.CampaignToAppendID;
    }

    public void setCampaignToAppendID(string c) {
        this.CampaignToAppendID = c;
//        system.debug('setCampaignToAppendID - CampaignToAppendID: '+this.CampaignToAppendID);
        if (CampaignToAppendID != '0') {
            Campaign TheCampaign = ([SELECT id, name FROM campaign where id = :this.CampaignToAppendID]);
//            system.debug ('Campaign to append: '+this.CampaignToAppendID+' - '+TheCampaign.name);
            }
    }

    public boolean getProcessEnded() {
        if (this.ProcessEnded == null) {
            this.ProcessEnded = True;           
        }
        return this.ProcessEnded;
    }

    public boolean getnoContact() {
        if (this.noContact == null) {
            this.noContact = True;           
        }
        return this.noContact;
    }
    public boolean getisContact() {
        if (this.isContact == null) {
            this.isContact = False;
        }
        return this.isContact;
    }
    
    public boolean getCampaignAlert() {
        if (CampaignAlert == null) {
            CampaignAlert = False;
        }
        return CampaignAlert;
    }
}

 

This is being used by the following page:

 

<apex:page standardController="contact" extensions="MassCreateLeadsFromContactsControllerExt" recordSetVar="contacts">
<script>
function confirmCancel() {
var isCancel = confirm("Are you sure you wish to cancel?");
if (isCancel) return true;
return false;
}
</script>

<apex:sectionHeader title="Mass Create Leads from Contacts"></apex:sectionHeader>
<apex:form >
<apex:pageBlock mode="edit">
<apex:pageBlockButtons >
<apex:commandButton value="Create leads" action="{!CreateLeadsFromContacts}" id="CLFC"/>
<apex:commandButton value="Cancel" action="{!Cancel}"/>
</apex:pageBlockButtons>

<apex:pageBlockSection title="Lead creation parameters" collapsible="false" columns="1">
<apex:pageBlockSectionItem >
<apex:outputLabel for="CampaignToAppendID">Attach resulting leads to campaign:</apex:outputLabel>
<apex:selectlist value="{!CampaignToAppendID}" multiselect="false" size="1">
<apex:selectOptions value="{!CampaignList}"/>
</apex:selectlist>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem rendered="{!CampaignAlert}">
<apex:outputLabel ><h1>Please select a campaign</h1></apex:outputLabel>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem rendered="{!noContact}">
<apex:outputLabel ><h1>There is no contact to process</h1></apex:outputLabel>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem rendered="{!isContact}">
<apex:outputLabel ><h1>Nb contacts to process: {!ContactNumber}</h1></apex:outputLabel>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem rendered="{!ProcessEnded}">
<apex:outputLabel ><h1>{!ContactsProcessed} Contacts were processed</h1></apex:outputLabel>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockSection title="Contacts" columns="1" rendered="{!isContact}">
<apex:pageBlockSectionItem >
<apex:dataTable value="{!SelectedContacts}" var="TheContact" rowClasses="odd,even" styleClass="tableClass" width="100%">
<apex:column >
<apex:facet name="header">Name</apex:facet>
<apex:outputText value="{!TheContact.name}"/>
</apex:column>
<apex:column >
<apex:facet name="header">Title</apex:facet>
<apex:outputText value="{!TheContact.title}"/>
</apex:column>
<apex:column >
<apex:facet name="header">email</apex:facet>
<apex:outputText value="{!TheContact.email}"/>
</apex:column>
</apex:dataTable>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

The purpose is to select the contacts in a view and trigger a wizard that creates a lead for each contact and add the newly created leads to a campaign (which name is being prompted to the user).

 

I tried to write a unit test class that creates a list of contacts and instantiates the controller extension, passing this list of contacts but I have not been able to find out how I can do this.

 

Any hint?

 

My (useless, I am afraid) test code so far:

 

Public class TestLeadMassCreationWizard {

    public static testMethod void testLeadMassCreation() {
        System.Debug('Debugging...');
        System.Debug('Unit Test: lead Mass Creation and addition to campaign');
               
        list<contact> Clist = [select ID from contact where lastname like 'M%' limit 5];
        Campaign thecampaign = [select ID from Campaign where isactive = true limit 1];
       
        MassCreateLeadsFromContactsControllerExt TheController = new MassCreateLeadsFromContactsControllerExt<Clist>();
       
        string nextpage = ssc.CreateLeadsFromContacts().getURL();
    }
}

bbrantly1bbrantly1

You need to pass it a standcontroller which you create via code, here is a quick sample:

 

 

contact c = new contact(PUT ALL INFO FOR CONTACT HERE);
ApexPages.StandardController sc = new ApexPages.StandardController(c);
MassCreateLeadsFromContactsControllerExt controller = new MassCreateLeadsFromContactsControllerExt(sc);

 

 You can also do:

 

contact c = [select id,field,field2 from contact where id='SOMEID'];
ApexPages.StandardController sc = new ApexPages.StandardController(c);
MassCreateLeadsFromContactsControllerExt controller = new MassCreateLeadsFromContactsControllerExt(sc);

 

 

Hard coding values isn't recommend though, becuase the test method will fail if the id doesn't exists.

 

mtbclimbermtbclimber

For the standardsetcontroller you can use the sobject-collection based constructor so your results are predictable according to the needs of your test. For example:

 

 

List<Contact> mycontacts = ...... ApexPages.StandardSetController setCon = new ApexPages.StandardSetController(mycontacts); mysetcontrollerextention ext = new mysetcontrollerextension(setcon);

 

 

 

Greg-inficienceGreg-inficience
This last one worked fine. Thx a lot.