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
Jill HedbergJill Hedberg 

Help Writing Test Class for Trigger

Hi,

 

Could you please help me write a test class for my trigger? I managed to get 10% covered, but since I am not a programmer I am having a hard time understanding how to correct it to get more. Thank you in advance!

 

This is my Trigger:

trigger CreateAssetonClosedWon on Opportunity (after insert, after update) {
     for(Opportunity o: trigger.new){ 
      if(o.isWon == true && o.HasOpportunityLineItem == true && o.RecordTypeId == '012200000004fxZ'){
         String opptyId = o.Id;
         OpportunityLineItem[] OLI = [Select UnitPrice, Quantity, PricebookEntry.Product2Id, PricebookEntry.Product2.Name, Description, Converted_to_Asset__c  
                                      From OpportunityLineItem 
                                      where OpportunityId = :opptyId and Converted_to_Asset__c = false];
         Asset[] ast = new Asset[]{};
         Asset a = new Asset();
         for(OpportunityLineItem ol: OLI){
            a = new Asset();
        a.AccountId = o.AccountId;
            a.Product2Id = ol.PricebookEntry.Product2Id;
            a.Quantity = ol.Quantity;
            a.Price =  ol.UnitPrice;
            a.PurchaseDate = o.CloseDate;
            a.Status = 'Purchased';
            a.Description = ol.Description;
            a.Name = ol.PricebookEntry.Product2.Name;
            ast.add(a);
            ol.Converted_to_Asset__c = true;
       }
      update OLI; 
      insert ast;
     }
    }
}

 

Jerun JoseJerun Jose

Please use this to start. First you will need to create test data for your trigger. Then you will need to simulate the test scenario to test your trigger, in this case you will need to update an opportunity with the stage as Closed.

 

@IsTest
public class testClassOpp{
	public static testmethod void test1(){
		Opportunity opp = new Opportunity();
		opp.RecordTypeId = '012200000004fxZ';
		opp.Name = 'test Oppty';
		opp.StageName = 'Opening';
		opp.CloseDate = system.today().addDays(10);
		insert opp;
		
		OpportunityLineItem oli = new OpportunityLineItem();
		oli.OpportunityID = opp.Id;
		oli.PriceBookEntryID = [select id from PriceBookEntry limit 1][0].ID;
		oli.Converted_to_Asset__c = false;
		oli.UnitPrice = 10;
		insert oli;
		
		Test.startTest();
			opp.StageName = 'Closed Won';
			update opp;
		Test.stopTest();
	}
}

 

 

Jill HedbergJill Hedberg
I changed the name of the class, the StageName to what we call the stage (A1 - Initiate ) and (A6 - Closed Won).

It gives an error message doing the test execusion:
Error Message: System.ListException: List index out of bounds: 0
Stack Trace: Class.testCreateAssetonClosedWon.testCreateAssetonClosedWon: line 13, column 1

Line 13 is " oli.PriceBookEntryID = [select id from PriceBookEntry limit 1][0].ID;"

What does it want me to change?
Jerun JoseJerun Jose

A quick fix for that would be to change

@IsTest

to

@IsTest(seealldata=true)

 

Vinit_KumarVinit_Kumar

You are missing SeeAllData=true in your test class.Please change from :-

 

@IsTest

 

to 

 

@IsTest(SeeAllData=true).

 

Also,you please make sure that you have active PricebookEntry in your org.

Jill HedbergJill Hedberg
Unfortunately that did not work. Now I get the error message:

Error Message: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: PricebookEntryId (pricebook entry is inactive): [PricebookEntryId]

Stack Trace: Class.testCreateAssetonClosedWon.testCreateAssetonClosedWon: line 16, column 1

Line 16 is the insert oli part
Jill HedbergJill Hedberg
We use the pricebook function today, so how can it be inactive? We also have products added to opportunitys in the test org. This is so confusing :)
vishal@forcevishal@force

oli.PriceBookEntryID = [select id from PriceBookEntry WHERE IsActive = TRUE limit 1][0].ID;

 

This should help!

Jill HedbergJill Hedberg
Thank you! But now I get this error message instead:

Error Message: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: PricebookEntryId (pricebook entry currency code does not match opportunity currency code): [PricebookEntryId]
Jill HedbergJill Hedberg

It seems I solved the currency error (no idea if it is the right way, but no error for that now) But then I got another error since before closing an opportunity we have to add a Delivery Contact under Contact Roles on the opportunity. Think I solved that too (no error message for that now).

But we also have to add a territory before closing. I have no idea how to get that into the test class. Anyone who can help? This is my test class code now.

@IsTest (seealldata=true)
public class testCreateAssetonClosedWon{
    public static testmethod void testCreateAssetonClosedWon(){
    
       PricebookEntry pbID = [select Id,CurrencyIsoCode from PricebookEntry limit 1];
             
       //create a dummy account
        Account a = new Account ();
        a.Name = 'Test Asset Account';
        insert a;
        
        //create a dummy opportunity
        Opportunity opp = new Opportunity();
        opp.AccountId = a.Id;
        opp.CurrencyIsoCode = pbID.CurrencyIsoCode;
        opp.RecordTypeId = '012200000004fxZ';
        opp.Name = 'test Oppty';
        opp.StageName = 'A1 - Initiate';
        opp.CloseDate = system.today();
        insert opp;
        
        //System.Debug(pbID.CurrencyIsoCode);
              
        //create products
        OpportunityLineItem oli = new OpportunityLineItem();
        oli.OpportunityID = opp.Id;
        oli.PriceBookEntryID = [select id, CurrencyIsoCode from PriceBookEntry WHERE IsActive = TRUE limit 1][0].ID;
        oli.Converted_to_Asset__c = false;
        oli.UnitPrice = 10.00;
        insert oli;
        
        //create contact
        Contact newContact = new Contact(Lastname='testLastName', AccountId = a.Id);
        insert newContact;
        
        //create delivery contact 
        OpportunityContactRole ocr = new OpportunityContactRole (OpportunityId = opp.Id, ContactId = newContact.Id, Role = 'Delivery Contact');
        insert ocr;
        
        Test.startTest();
            opp.StageName = 'A6 - Closed Won';
            update opp;
        Test.stopTest();
    }
}

 

Also please let me know if it does not do what it is supposed to now. I have no idea what I am doing...

I am guessing I have to make the opportunity close since that is when the products get automatically turned into assets on the account page? But I have never had to add a territory to a test class before which makes me question if this really is the correct way to do it.

Jill HedbergJill Hedberg
Never mind! I got it to work :D Wiihooo

Now have a 100% code coverage!
jbardetjbardet

I have something similar going on. Can you post your final code?

 

@isTest
private Class ForceLIUpdate
{

public static testmethod void testOpportunityTrigger()
{

// In your testmethod you need to create first Account & Opportunity record like
 
Account acc=new Account(Name='Test');


insert acc;
 
Opportunity Oppp=new Opportunity();
oppp.Name='Oppabc';
oppp.Type='New Manufacture';
oppp.RFQ_Received__c=date.today();
oppp.AccountId=acc.id;


oppp.StageName='Closed Won';
oppp.CloseDate=Date.today().addDays(15);
oppp.Send_Quote_By__c=date.today();

insert oppp;

//retrieving the objects I need for creating the OLI.
PricebookEntry pbe1 = [select id from PricebookEntry LIMIT 1];

// Next, it insert a new 2 opportunity product

OpportunityLineItem[] Oli=new OpportunityLineItem[]{};


oli.add(new OpportunityLineItem(Opportunityid=oppp.id,pricebookentryid=pbe1.id,Quantity=1 ,UnitPrice=1000));

insert Oli;


test.startTest();

Oppp.SO_Opened__c = date.today();
update oppp;



test.stopTest();
}

}

 

I tried deploying in production a new field and workflow and workflow field update, and it resulted in the following error:

 

Failure Message: "System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: PricebookEntryId (pricebook entry is inactive): [PricebookEntryId]", Failure Stack Trace: "Class.ForceLIUpdate.testOpportunityTrigger: line 38, column 1"