+ Start a Discussion
Marvin Castro 8Marvin Castro 8 

How do I create a Test Class for this code?

Hello, I am new to salesforce and writing my first Test Class.  I created this code in Dev and unable to push to production due needing to create a test class.  Below is the code.  

I appreciate the assistance.

Marvin

trigger changeLeadStatus on Task (before insert, before update) {
    String desiredNewLeadStatus = 'Working';

    List<Id> leadIds=new List<Id>();
    for(Task t:trigger.new){
        if(t.Status=='Completed'){
            if(String.valueOf(t.whoId).startsWith('00Q')==TRUE){//check if the task is associated with a lead
                leadIds.add(t.whoId);
            }//if 2
        }//if 1
    }//for
    List<Lead> leadsToUpdate=[SELECT Id, Status FROM Lead WHERE Id IN :leadIds AND IsConverted=FALSE];
    For (Lead l:leadsToUpdate){
        l.Status=desiredNewLeadStatus;
    }//for
    
    try{
        update leadsToUpdate;
    }catch(DMLException e){
        system.debug('Leads were not all properly updated.  Error: '+e);
    }
}//trigger

 
UC InnovationUC Innovation
Hi Marvin,

Typically the minimum amount of coverage necessary to push a trigger to production is >0% but I would recommend going for the full 100 just to prevent any issues with coverage later (such as falling below minimum total coverage of 75%). Try this out and make some modification to the code as needed. Made some comments to help with this.
 
@isTest
private class TestChangeLeadStatus {
    static testMethod void testTaskTrigger() {
		Lead TestLead = new Lead();
		testLead.IsConverted = false;
		// Other required fields here
		insert testLead;
		
		Task testTask = new Task();
		testTask.Status = 'Completed';
		testTask.whoId = testLead.Id;
		// Other required fields here
		
		// Test code within
		Test.startTest();
		insert testLead
		Test.stopTest();
	}
}


Hope this helps!

AM