Search code examples
triggerssalesforceapex-code

What is wrong in my Salesforce Trigger Test Class?


I have written a simple SalesForce Trigger. I want to update the IsUnreadbyOwner field to False once a lead becomes unqualified (this happens as our users leave the leads in the queue).

My Trigger is:

trigger UnqualifiedLead on Lead (after update) {
    for(Lead lead: Trigger.new)
    {
        if (lead.Status == 'Unqualified')
        {
            lead.IsUnreadByOwner = False;   
        }
    }
}

My Test class, AFAIK should look like this:

@isTest
private class UnqualifiedLeadTest {
static testMethod void myUnitTest() {
        // Setup the lead record
        Lead lead = new Lead();
        lead.LastName = 'last';
        lead.FirstName = 'First';
        lead.Company = 'Company';
        lead.Status = 'Unqualified';
        lead.IsUnreadByOwner = True;
        insert lead;
    }
}

However, I get a coverage error: 0% covered.

Where is my mistake?


Solution

  • In your test class you are only inserting the record yet your trigger is only setup to capture update events. You will either need to insert the lead then update to execute your trigger or add "on insert" to your trigger so that it runs when a lead is inserted and updated.

    Also, you are using an after event when you should be using a before event trigger for this type of update. Saves having to perform an additional DML operation.