[SalesForce] How to Write a Test Class for an InvocableMethod

I have a simple invocable method (thanks, Rakesh Gupta!) that I'm calling from a Process Builder when certain criteria are met. I'm getting good results from the code as evidenced by reviewing data in the UI, but I'm not sure how to write a test class for an @InvocableMethod.

Here is the invocable method:

public class AssignLeadsUsingAssignmentRules
 {
    @InvocableMethod
    public static void LeadAssign(List<Id> LeadIds)
    {
        Database.DMLOptions dmo = new Database.DMLOptions();
        dmo.assignmentRuleHeader.useDefaultRule= true;          
        Lead Leads=[select id from lead where lead.id in :LeadIds];
        Leads.setOptions(dmo);
        update Leads;
    }
 }

Here is test class that I've written:

@isTest
private class AssignLeadsUsingAssignmentRulesTest {

    private static testMethod void doTest() {

        Test.startTest();
        Lead l = new Lead(LastName = 'Test Lead',
                     Company = 'Test Company',
                     IsRecruitmentLead__c = True);
        insert l;
        Test.stopTest();

    }
}

The test class creates data that meets the criteria for the Process Builder, and the test class executes to completion in the Developer Console, but I'm still getting 0% code coverage for the invocable class.

Thanks in advance for your advice –
Tom

Best Answer

Not sure if these methods get invoked automatically or not but you could invoke it directly in your test.....

Also, you need some asserts to make sure what you expect to happens does. Simply executing code is not a test at all...

@isTest
private class AssignLeadsUsingAssignmentRulesTest {

    private static testMethod void doTest() {

        Test.startTest();
        Lead l = new Lead(LastName = 'Test Lead',
                     Company = 'Test Company',
                     IsRecruitmentLead__c = True);
        insert l;

        AssignLeadsUsingAssignmentRules.leadAssign(New Lead[]{l});

        Test.stopTest();

        l = [Select OwnerID From Lead where ID = :l.id];
        system.assertEquals(WHATYOUEXPECT, l.OwnerID);

    }
}
Related Topic