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
Nick SpeyerNick Speyer 

Test Class - Need to convert a lead object to an opportunity

Hi All,

I've got a trigger i've been working on that does all the requirements I need it to. I am at the final stretch of deployment and need to write a test method that will give me adequate code coverage to deploy.

The basis of the code is very similar to a VLOOKUP function. I have a set of 700+ records which include a zip code in the name field and a specific "Load Zone" in the second field. My code keys off of an updated parcel zip code in the opportunity object as a reference and returns the proper load zone for that zip code from the list of records - again, much like a VLOOKUP. I now have to develop test methods to ensure code coverage. Is anybody willing to help?

The Trigger is as follows:

Parcel_Zip__c is the field in Opportunity being referenced in the Load_U__c object that holds the name field being searched through and returning the corresponding Load_Zone__c field's value into the Load_Zone_Utility_4__C field in the opportunity object.
 
Trigger updateLZU on Opportunity (before insert, before update) {

	set <string> ZipCodes = new Set <string>( ); 
	//creates a set labeled zip codes to hold the Parcel Zip Codes being referenced 

	for ( opportunity l : trigger.new) {
	
		If ( l.Parcel_Zip__c != null) {
	
			ZipCodes.add (l.Parcel_Zip__c);}
	}
	//loads the Parcel Zip Code field values into the ZipCodes set using a for loop that starts when the Parcel Zip Code contains a value.

	if ( ZipCodes.size( ) > 0 ) {
	
		map <string, Load_u__c> validLZU = new map <string, Load_u__c> ( );
		//creates a map labeled validLZU with a key of string data type and a value in the Load Zone & Utilites object.
		
		for (Load_u__c obj : [SELECT Id, name, Load_Zone__C 
                                                  FROM Load_u__C 
                                                  WHERE name
                                                  IN : ZipCodes] ) {
		//creates a for loop that queries the Load Zone & Utilities’ object records for the matching  zip code being stored in the ZipCodes set and returns the name and Load Zone fields.

			validLZU.put (obj.name, obj); 
			//loads the name (zip code) returned by the query into the key value of the validLZU map and loads the query as the map’s value.
		}
		
	for ( opportunity l : trigger.new) {

		if ( trigger.isInsert || trigger.oldMap.get(l.Id).ZipCode != l.Parcel_Zip__c && validLZU.containsKey (l.Parcel_Zip__c)) {
		// if the parcel zip code is inserted or if the parcel zip code is different than what it used to be and the map contains a name equal to the parcel zip code than execute:

			l.load_zone_utility_4__C = validLZU.get (l.Parcel_Zip__c).Load_Zone__C;
			//set the Load Zone & Utility field in the opportunity object to the corresponding Load Zone & utility field in the Load Zone & Utility object depending on the parcel zip code.
			
		}

		else if(trigger.oldMap.get(l.iD).Parcel_Zip__c != l.Parcel_Zip__c && !validLZU.containsKey(l.Parcel_Zip__c)) {
		// if the old parcel zip code is equal to the current parcel zip code and the map does not contain the parcel zip code execute:

			l. load_zone_utility_4__C __C = null;
			//set the Load Zone & Utility field in the opportunity object to null.
	}
}
}
}

My test class is as follows:
 
@isTest
private class leadsLZUTriggerTestClass {

Static testMethod void validateLZUL(){

lead newLead = new lead(firstName = ‘James’, lastName = ‘Sullivan’, company = ‘Walmart’, status = 'contacted', Parcel_Zip__c = '02052') ;
Load_U newLZU = new Load_U ( name = '02052', Load_zone__c= 'NEMA Eversource');

//create new Load Zone and Lead objects to be used in the test.

newLead.FirstName = 'Cole';
newLead.LastName = 'Swain';
newLead.Company = 'BlueWave';
newLead.Status = 'contacted';
newLead.Parcel_Zip__C = '02052';

//update the new lead’s field values

newLZU.name = '02052';
newLZU.Load_Zone__c = 'NEMA Eversource';

//update the new load zone’s fields values

test.startTest();
 
insert newLead;

database.leadConvert lc = new database.leadConvert();
lc.setLeadId(newLead.id);

leadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
lc.setConvertedStatus(convertStatus.MasterLabel);

Database.LeadConvertResult lcr = Database.convertLead(lc);
System.assert(lcr.isSuccess());

lc.setOpportunityName(‘James Sullivan’);

//convert the new lead into an opportunity object and set its name to ‘James Sullivan’
 
test.stopTest();
 
opportunity opQuery = [SELECT name, Load_Zone_Utility_4__c FROM opportunity WHERE name = ‘James Sullivan];

//query the opportunity object for records with the name = ‘James Sullivan’ and return name and Load Zone
 
system.assertEquals('NEMA Eversource', opQuery. Load_Zone_Utility_4__c);
 
//assert that the outcome is correct
 
}
}

I am having trouble with the conversion piece of the code. I want to convert the created lead into an opportunity, then reference this opportunity using a query. 

I receive the following error message when I run the test:

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, updateLZUL: execution of BeforeInsert

caused by: System.NullPointerException: Attempt to de-reference a null object

Trigger.updateLZUL: line 25, column 1: []

Anybody have any idea what I am doing wrong? 
Best Answer chosen by Nick Speyer
Amit Chaudhary 8Amit Chaudhary 8
Now try below code in Test Class:-
@isTest
private class opp3LZUTriggerTestClass 
{
 
Static testMethod void validateLZU()
{

        Load_U__c newLZU = new Load_U__c ( name = '02052', Load_zone__c= 'NEMA Eversource');
        newLZU.name = '02052';
        newLZU.Load_Zone__C = 'NEMA Eversource';
        insert newLZU;

        lead newLead = new lead(firstName = 'Cole', lastName = 'Swain', company = 'BlueWave', status = 'contacted', Parcel_Zip__c = '02052') ;
        newLead.FirstName = 'Cole';
        newLead.LastName = 'Swain';
        newLead.Company = 'BlueWave';
        newLead.Status = 'contacted';
        newLead.Parcel_Zip__C = '02052';
        insert newLead;
 
 
        test.startTest();
 
               database.leadConvert lc = new database.leadConvert();
               lc.setLeadId(newLead.id);
 
               leadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
                lc.setConvertedStatus(convertStatus.MasterLabel);
 
               Database.LeadConvertResult lcr = Database.convertLead(lc);
               System.assert(lcr.isSuccess());
 
               lc.setOpportunityName('Cole Swain');
 
         
        test.stopTest();
        
               opportunity opQuery = [SELECT name, Load_Zone_Utility_4__c FROM opportunity WHERE name = 'Cole Swain'];
               system.assertEquals('NEMA Eversource', opQuery.Load_Zone_Utility_4__c);
 
 
}
}

Also Fix your Trigger code :-
 
Trigger updateLZUL on Lead (before insert, before update) {

    set <string> ZipCodes = new Set <string>( ); 

    for ( Lead l : trigger.new) {
    
        If ( l.Parcel_Zip__c != null) {
    
            ZipCodes.add (l.Parcel_Zip__C);}
    }

    if ( ZipCodes.size( ) > 0 ) {
    
        map <string, Load_u__c> validLZU = new map <string, Load_u__c> ( );
        
        for (Load_u__c obj : [SELECT Id, name, Load_Zone__C FROM Load_u__C WHERE name IN : ZipCodes] ) {

            validLZU.put (obj.name, obj); 
        }

    for ( Lead l : trigger.new) {

        if ( trigger.isInsert || trigger.oldMap.get(l.Id).Parcel_Zip__c != l.Parcel_Zip__C ) 
		{
			if( validLZU.containsKey (l.Parcel_Zip__c) )
			{
				l.LZU__c = validLZU.get (l.Parcel_Zip__C).Load_Zone__C;
			}	
        }

        else if(trigger.oldMap.get(l.iD).Parcel_Zip__c != l.Parcel_Zip__C && !validLZU.containsKey(l.Parcel_Zip__C)) 
		{

            l.LZU__C = null;
		}
	}
}
}

Pleae mark this as best solution if this will help you.

Please let know if you need any other help

Thanks
Amit Chaudhary
amit.salesforce21@gmail.com
 

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Please try below test class
 
@isTest
private class leadsLZUTriggerTestClass 
{

Static testMethod void validateLZUL()
{

	lead newLead = new lead(firstName = ‘James’, lastName = ‘Sullivan’, company = ‘Walmart’, status = 'contacted', Parcel_Zip__c = '02052') ;

	//create new Load Zone and Lead objects to be used in the test.

	newLead.FirstName = 'Cole';
	newLead.LastName = 'Swain';
	newLead.Company = 'BlueWave';
	newLead.Status = 'contacted';
	newLead.Parcel_Zip__C = '02052';
	insert newLead;


	Load_U newLZU = new Load_U ( name = '02052', Load_zone__c= 'NEMA Eversource');
	newLZU.name = '02052';
	newLZU.Load_Zone__c = 'NEMA Eversource';
	insert newLZU;

	test.startTest();

		database.leadConvert lc = new database.leadConvert();
		lc.setLeadId(newLead.id);

		leadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
		lc.setConvertedStatus(convertStatus.MasterLabel);

		Database.LeadConvertResult lcr = Database.convertLead(lc);
		System.assert(lcr.isSuccess());

		lc.setOpportunityName(‘James Sullivan’);

	 
	test.stopTest();
	
		opportunity opQuery = [SELECT name, Load_Zone_Utility_4__c FROM opportunity WHERE name = ‘James Sullivan];
		system.assertEquals('NEMA Eversource', opQuery. Load_Zone_Utility_4__c);
 
 
}
}

Let us know if this will help you
 
Nick SpeyerNick Speyer
Hi Amit,

Thank you for your help, I do appreciate it. I see how you changed the code and I definitly think it makes more sense. 

I received the following error message when I ran the code. 
 
Method Name	validateLZUL
Pass/Fail	Fail
Error Message	System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, updateLZUL: execution of BeforeInsert

caused by: System.NullPointerException: Attempt to de-reference a null object

Trigger.updateLZUL: line 25, column 1: []
Stack Trace	Class.opp3LZUTriggerTestClass.validateLZUL: line 17, column 1

Any thoughts? 
Nick SpeyerNick Speyer
Absolutely.
 
@isTest
private class opp3LZUTriggerTestClass 
{
 
Static testMethod void validateLZU()
{
        lead newLead = new lead(firstName = 'Cole', lastName = 'Swain', company = 'BlueWave', status = 'contacted', Parcel_Zip__c = '02052') ;
 
        //create new Load Zone and Lead objects to be used in the test.

        newLead.FirstName = 'Cole';
        newLead.LastName = 'Swain';
        newLead.Company = 'BlueWave';
        newLead.Status = 'contacted';
        newLead.Parcel_Zip__C = '02052';
        insert newLead;
 
 
        Load_U__c newLZU = new Load_U__c ( name = '02052', Load_zone__c= 'NEMA Eversource');
        newLZU.name = '02052';
        newLZU.Load_Zone__c = 'NEMA Eversource';
        insert newLZU;
 
        test.startTest();
 
               database.leadConvert lc = new database.leadConvert();
               lc.setLeadId(newLead.id);
 
               leadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
                lc.setConvertedStatus(convertStatus.MasterLabel);
 
               Database.LeadConvertResult lcr = Database.convertLead(lc);
               System.assert(lcr.isSuccess());
 
               lc.setOpportunityName('Cole Swain');
 
         
        test.stopTest();
        
               opportunity opQuery = [SELECT name, Load_Zone_Utility_4__c FROM opportunity WHERE name = 'Cole Swain'];
               system.assertEquals('NEMA Eversource', opQuery.Load_Zone_Utility_4__c);
 
 
}
}

The updateLZU trigger is as follows:
 
Trigger updateLZU on Opportunity (before insert, before update) {

    set <string> ZipCodes = new Set <string>( ); 

    for ( opportunity l : trigger.new) {
    
        If ( l.Parcel_Zip__C != null) {
    
            ZipCodes.add (l.Parcel_Zip__C);}
    }

    if ( ZipCodes.size( ) > 0 ) {
    
        map <string, Load_u__c> validLZU = new map <string, Load_u__c> ( );
        
        for (Load_u__c obj : [SELECT Id, name, Load_Zone__C FROM Load_u__C WHERE name IN : ZipCodes] ) {

            validLZU.put (obj.name, obj); 
        }

    for ( opportunity l : trigger.new) {

        if ( trigger.isInsert || trigger.oldMap.get(l.Id).Parcel_Zip__C != l.Parcel_Zip__C && validLZU.containsKey (l.Parcel_Zip__C)) {

            l.Load_Zone_Utility_4__c = validLZU.get (l.Parcel_Zip__C).Load_Zone__C;
        }

        else if(trigger.oldMap.get(l.iD).Parcel_Zip__C != l.Parcel_Zip__C && !validLZU.containsKey(l.Parcel_Zip__C)) {

            l.Load_Zone_Utility_4__c = null;
    }
}
}
}

From what I can tell, the class is referencing the wrong trigger - I want it to test updateLZU; however from the error message it looks as if it is testing updateLZUL.
Nick SpeyerNick Speyer
updateLZUL Trigger code is as follows:
 
Trigger updateLZUL on Lead (before insert, before update) {

    set <string> ZipCodes = new Set <string>( ); 

    for ( Lead l : trigger.new) {
    
        If ( l.Parcel_Zip__c != null) {
    
            ZipCodes.add (l.Parcel_Zip__C);}
    }

    if ( ZipCodes.size( ) > 0 ) {
    
        map <string, Load_u__c> validLZU = new map <string, Load_u__c> ( );
        
        for (Load_u__c obj : [SELECT Id, name, Load_Zone__C FROM Load_u__C WHERE name IN : ZipCodes] ) {

            validLZU.put (obj.name, obj); 
        }

    for ( Lead l : trigger.new) {

        if ( trigger.isInsert || trigger.oldMap.get(l.Id). Parcel_Zip__c != l.Parcel_Zip__C && validLZU.containsKey (l.Parcel_Zip__c)) {

            l.LZU__c = validLZU.get (l.Parcel_Zip__C).Load_Zone__C;
        }

        else if(trigger.oldMap.get(l.iD).Parcel_Zip__c != l.Parcel_Zip__C && !validLZU.containsKey(l.Parcel_Zip__C)) {

            l.LZU__C = null;
    }
}
}
}

 
Amit Chaudhary 8Amit Chaudhary 8
Now try below code in Test Class:-
@isTest
private class opp3LZUTriggerTestClass 
{
 
Static testMethod void validateLZU()
{

        Load_U__c newLZU = new Load_U__c ( name = '02052', Load_zone__c= 'NEMA Eversource');
        newLZU.name = '02052';
        newLZU.Load_Zone__C = 'NEMA Eversource';
        insert newLZU;

        lead newLead = new lead(firstName = 'Cole', lastName = 'Swain', company = 'BlueWave', status = 'contacted', Parcel_Zip__c = '02052') ;
        newLead.FirstName = 'Cole';
        newLead.LastName = 'Swain';
        newLead.Company = 'BlueWave';
        newLead.Status = 'contacted';
        newLead.Parcel_Zip__C = '02052';
        insert newLead;
 
 
        test.startTest();
 
               database.leadConvert lc = new database.leadConvert();
               lc.setLeadId(newLead.id);
 
               leadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
                lc.setConvertedStatus(convertStatus.MasterLabel);
 
               Database.LeadConvertResult lcr = Database.convertLead(lc);
               System.assert(lcr.isSuccess());
 
               lc.setOpportunityName('Cole Swain');
 
         
        test.stopTest();
        
               opportunity opQuery = [SELECT name, Load_Zone_Utility_4__c FROM opportunity WHERE name = 'Cole Swain'];
               system.assertEquals('NEMA Eversource', opQuery.Load_Zone_Utility_4__c);
 
 
}
}

Also Fix your Trigger code :-
 
Trigger updateLZUL on Lead (before insert, before update) {

    set <string> ZipCodes = new Set <string>( ); 

    for ( Lead l : trigger.new) {
    
        If ( l.Parcel_Zip__c != null) {
    
            ZipCodes.add (l.Parcel_Zip__C);}
    }

    if ( ZipCodes.size( ) > 0 ) {
    
        map <string, Load_u__c> validLZU = new map <string, Load_u__c> ( );
        
        for (Load_u__c obj : [SELECT Id, name, Load_Zone__C FROM Load_u__C WHERE name IN : ZipCodes] ) {

            validLZU.put (obj.name, obj); 
        }

    for ( Lead l : trigger.new) {

        if ( trigger.isInsert || trigger.oldMap.get(l.Id).Parcel_Zip__c != l.Parcel_Zip__C ) 
		{
			if( validLZU.containsKey (l.Parcel_Zip__c) )
			{
				l.LZU__c = validLZU.get (l.Parcel_Zip__C).Load_Zone__C;
			}	
        }

        else if(trigger.oldMap.get(l.iD).Parcel_Zip__c != l.Parcel_Zip__C && !validLZU.containsKey(l.Parcel_Zip__C)) 
		{

            l.LZU__C = null;
		}
	}
}
}

Pleae mark this as best solution if this will help you.

Please let know if you need any other help

Thanks
Amit Chaudhary
amit.salesforce21@gmail.com
 
This was selected as the best answer
Nick SpeyerNick Speyer
Amit,

Thank you for your help. Smart maneuver in the trigger. I would not have thought to do that.

The following error message just came up:

Error Message System.QueryException: List has no rows for assignment to SObject

This sounds minor. Any idea?

 
Amit Chaudhary 8Amit Chaudhary 8

Error Message System.QueryException: List has no rows for assignment to SObject

Means your are query data in any object and zere record. 
Please post your code where you are getting error
 
Nick SpeyerNick Speyer
opp3LZUTriggerClass
 
@isTest
private class opp3LZUTriggerTestClass 
{
 
Static testMethod void validateLZU()
{

        Load_U__c newLZU = new Load_U__c ( name = '02052', Load_zone__c= 'NEMA Eversource');
        newLZU.name = '02052';
        newLZU.Load_Zone__C = 'NEMA Eversource';
        insert newLZU;

        lead newLead = new lead(firstName = 'Cole', lastName = 'Swain', company = 'BlueWave', status = 'contacted', Parcel_Zip__c = '02052') ;
        newLead.FirstName = 'Cole';
        newLead.LastName = 'Swain';
        newLead.Company = 'BlueWave';
        newLead.Status = 'contacted';
        newLead.Parcel_Zip__C = '02052';
        insert newLead;
 
 
        test.startTest();
 
               database.leadConvert lc = new database.leadConvert();
               lc.setLeadId(newLead.id);
 
               leadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
                lc.setConvertedStatus(convertStatus.MasterLabel);
 
               Database.LeadConvertResult lcr = Database.convertLead(lc);
               System.assert(lcr.isSuccess());
 
               lc.setOpportunityName('Cole Swain');
 
        test.stopTest();
               
               opportunity opQuery = [SELECT name,Load_Zone_Utility_4__c FROM opportunity WHERE Name = 'Cole Swain'];
               system.assertEquals('NEMA Eversource', opQuery.Load_Zone_Utility_4__c);
 
 
}
}

 
Nick SpeyerNick Speyer
Amit,

Thank you for your help. 

I was able to fix this issue by changing the class version to 20.