+ Start a Discussion
San Diego CraigSan Diego Craig 

Apex unit test class - how to programmatically add custom Lookup field values to a Lead?

  • On the Lead object, I created a custom field called “Product_1__c”, which is a Lookup field to the Product object
  • I have successfully created a trigger that moves the Product from the Lead to the Opportunity during the Convert process


Problem:  In my Apex test class, how do I programmatically add the custom field “Product_1__c” to the Lead, and then invoke the Convert process?


Apex Unit Test code:


private class testTrgLeadConvert {
    static testMethod void myUnitTest() {       



// Create the Lead object...

Lead lead = new Lead();       

lead.LastName = 'Test LastName';       

lead.Company = 'Test Company';       

insert lead;               


// make an update....

lead.Status = 'Qualified Lead';       

lead.Number_of_Reps__c = 10;       

lead.Industry = 'Banking';       

update lead;               


// test to ensure update worked...

Lead updatedLead = [SELECT Id, LastName, Company, Status, Industry FROM Lead Where Id = :lead.Id];       

System.assertEquals('Banking', updatedLead.Industry);               


// convert the Lead...

Database.Leadconvert leadConvert = new Database.Leadconvert();       


leadConvert.setConvertedStatus('Qualified Lead');       



Database.Leadconvertresult lcr = Database.convertLead(leadConvert);       

System.debug('leadConvert' + lcr.isSuccess());


Opportunity o = [SELECT Id, OwnerId FROM Opportunity WHERE Id=:lcr.getOpportunityId()];    

System.debug('opportunity ID:  ' + o.Id);        test.stopTest();   





trigger trgLeadConvert on Lead (after insert, after update) {
// products & opportunities   

set<Id> products = new Set<Id>();   

set<id> opportunities = new set<id>();             


// product to pricebook entries   

map<id,pricebookentry> pricebookentries = new map<id,pricebookentry>();             


// line items to add   

list<opportunitylineitem> lineitems = new list<opportunitylineitem>();             


// standard pricebook   

pricebook2 standardpricebook = [select id from pricebook2 where isstandard = true];

// get all of the Lead object's product and opportunity id values    

for(lead l : trigger.new) {       







// map product id to pricebook entry...  join the Lead's Product w/ the Pricebook Entry   

for(pricebookentry pbe:[select id, unitprice, product2id                            

  from pricebookentry                            

  where pricebook2.isstandard = true                              

     and product2id in :products]) {       

pricebookentries.put(pbe.product2id, pbe);   


// set pricebook entry value for opportunities   

for(opportunity[] opps:[select id from opportunity where id in :opportunities]) {       

for(opportunity opp:opps) {           

opp.pricebook2id = standardpricebook.id;       


update opps;   


// create line items   

for(lead l:trigger.new) {       

if(l.convertedopportunityid == null || l.Product_1__c == null) continue;       

lineitems.add(new opportunitylineitem(quantity=1,totalprice=pricebookentries.get(l.Product_1__c).unitprice,opportunityid=l.convertedopportunityid,pricebookentryid=pricebookentries.get(l.Product_1__c).id));               if(l.Product_2__c == null) continue;       

lineitems.add(new opportunitylineitem(quantity=1,totalprice=pricebookentries.get(l.Product_2__c).unitprice,opportunityid=l.convertedopportunityid,pricebookentryid=pricebookentries.get(l.Product_2__c).id));
       if(l.Product_3__c == null) continue;       

lineitems.add(new opportunitylineitem(quantity=1,totalprice=pricebookentries.get(l.Product_3__c).unitprice,opportunityid=l.convertedopportunityid,pricebookentryid=pricebookentries.get(l.Product_3__c).id));
       if(l.Product_4__c == null) continue;       

lineitems.add(new opportunitylineitem(quantity=1,totalprice=pricebookentries.get(l.Product_4__c).unitprice,opportunityid=l.convertedopportunityid,pricebookentryid=pricebookentries.get(l.Product_4__c).id));}     

// commit line items to the database   

insert lineitems;    








You should just be able to query a product from the standard price book:


Pricebook2 pb = [select id from pricebook2 where isstandard = true];
PricebookEntry pbe = [select id, Product2Id from PricebookEntry where Pricebook2.id=pb.id limit 1];



Craig PCraig P



thanks for the response.


when I try to implement the second line of code, the IDE is reporting an error:  "unexpected token 'pBook.Id'"


Pricebook2 pBook = [SELECT id FROM Pricebook2 WHERE IsStandard = true];       

PricebookEntry pbEntry = [SELECT id, Product2Id FROM PricebookEntry WHERE Pricebook2.Id = pBook.Id limit 1];


Am I missing an additional statement or parameter?  

Craig PCraig P

Quick update...  I used a different approach to get the PricebookEntries.  Works well.



The question I have now is how to get a handle of the product2Id from a Set to assign to the Lead object?


// add Products to Lead...

Pricebook2 standardPriceBook = [SELECT id FROM Pricebook2 WHERE IsStandard = true];


// get the Product IDs to assign to the Lead...

map<id,pricebookentry> priceBookEntries = new map<Id, PricebookEntry>();


for(pricebookentry pbe:[select id, unitprice, product2id from pricebookentry where pricebook2.isstandard = true]) {

priceBookEntries.put(pbe.product2id, pbe);


// update Lead object w/ Products...

lead.Product_1__c = priceBookEntries.get(0).product2Id;

lead.Product_2__c = priceBookEntries.get(1).product2Id;

lead.Product_3__c = priceBookEntries.get(2).product2Id;

lead.Product_4__c = priceBookEntries.get(3).product2Id;


update lead;

Craig PCraig P

Doh!  Easy solution, instead of using a Map, I used a List instead... :)


Code below:

// Use List to store Product IDs that will be assigned to the Lead...

List<Id> entries = new List<Id>();


for(pricebookentry pbe:[select id, unitprice, product2id from pricebookentry where pricebook2.isstandard = true]) {



// update Lead object w/ Products...

lead.Product_1__c = entries.get(0);

lead.Product_2__c = entries.get(1);

lead.Product_3__c = entries.get(2);

lead.Product_4__c = entries.get(3);       


update lead;