You need to sign in to do that
Don't have an account?
Edward Prignano
Help writing a test class for two triggers
I have two triggers that I copied and pasted that work perfectly, but I don't know the first thing about writing a test class to move them in to production. Can anyone help out please? Here are my two triggers:
Thank you!
trigger QuoteCreator on Opportunity (after insert) { for (Opportunity o : Trigger.new) { Quote q = new Quote(); q.name = 'Quote-' + o.name; q.opportunityId = o.id; insert q; } }
trigger AddEquipment on Opportunity (before insert, after insert) { Pricebook2 standardBook = [SELECT Id FROM Pricebook2 WHERE IsStandard = true]; if(Trigger.isBefore) { for(Opportunity record: Trigger.new) { record.Pricebook2Id = standardBook.Id; } } if(Trigger.isAfter) { OpportunityLineItem[] lines = new OpportunityLineItem[0]; PricebookEntry entry = [SELECT Id, UnitPrice FROM PricebookEntry WHERE Pricebook2Id = :standardBook.Id AND Product2.ProductCode = 'L5000ADTLB']; for(Opportunity record: Trigger.new) { lines.add(new OpportunityLineItem(PricebookEntryId=entry.Id, OpportunityId=record.Id, UnitPrice=entry.UnitPrice, Quantity=1)); } insert lines; } if(Trigger.isAfter) { OpportunityLineItem[] lines = new OpportunityLineItem[0]; PricebookEntry entry = [SELECT Id, UnitPrice FROM PricebookEntry WHERE Pricebook2Id = :standardBook.Id AND Product2.ProductCode = '5816WMWH']; for(Opportunity record: Trigger.new) { lines.add(new OpportunityLineItem(PricebookEntryId=entry.Id, OpportunityId=record.Id, UnitPrice=entry.UnitPrice, Quantity=1)); } insert lines; } }
Thank you!
The first place you should go is the Apex Testing module on Trailhead: https://trailhead.salesforce.com/module/apex_triggers. This module includes tips on testing triggers.
In a nutshell you test triggers by creating a unit test that inserts records around the object the triggers fire on. Then, you use SOQL queries to verify the data is correct.
In your case, the unit test should create at least one opportunity (Ideally you would use a loop in your unit test to insert 200+ records for testing bulk loads). Then you'd use SOQL to query and make sure the Quote and OpportunityLineItem records were created.
Hope that helps.
Replace both the triggers with the one below (ideally you should have single trigger on object for better performance and better control on sequence of execution)
Once done, below test class can help you to get the required coverage.
That should solve your problem.
If that works, then mark this as an answer for benefit of others.