You need to sign in to do that
Don't have an account?

Help structuring test class for Apex Trigger
I have developed a test class which automatically converts opportunity products to assets taking dependant values as seen below:
I am having trouble structuring my test class but ive finally worked out my errors. I think I am missing something. Test class is shown below
trigger OpportunityAssetonClosedWon on Opportunity (after insert, after update) { for(Opportunity o: trigger.new){ if(o.isWon==true && o.HasOpportunityLineItem==true){ String opptyId = o.Id; OpportunityLineItem[] OLI = [Select UnitPrice, Quantity, PricebookEntry.Product2Id, Product2.Name, Product2.Family, PricebookEntry.Product2.Name From OpportunityLineItem WHERE OpportunityId=:opptyId]; Asset[] ast = new Asset[]{}; Asset a = new Asset(); for(OpportunityLineItem ol: OLI){ if(ol.Product2.Family=='Terminal' || ol.Product2.Family=='Gateway' ){ a = new Asset(); a.AccountId = o.AccountId; a.Product2Id= ol.PricebookEntry.Product2Id; a.Quantity= 1; a.Price= ol.UnitPrice; a.PurchaseDate=o.CloseDate; a.status='Purchased'; a.Name = ol.Product2.Name; ast.add(a); ol.Converted_to_Asset__c = true; } } update OLI; insert ast; } } }
I am having trouble structuring my test class but ive finally worked out my errors. I think I am missing something. Test class is shown below
@isTest public class OpportunityAssetonClosedWonTest { static testMethod void closedOpportunity() { Account testAcc = new Account( Name = 'TestAccount' ); insert testAcc; Pricebook2 p = new Pricebook2( Name = 'Testbook'); insert p; Opportunity testOpportunity = new Opportunity( StageName = 'Sourcing Demand', CloseDate = Date.newInstance(2017,12,31), AccountId = testAcc.Id, Name = 'Test Opportunity Triggers', Pricebook2Id=p.id ); insert testOpportunity; Product2 p1 = new Product2( Name = 'prod1', Family = 'Terminal'); insert p1; PricebookEntry pE = new PricebookEntry( Pricebook2Id=p.Id, Product2Id=p1.Id); Product2 p2 = new Product2( Name='prod2', Family='Gateway'); insert p2; PricebookEntry pE2 = new PricebookEntry( Pricebook2Id=p.Id, Product2Id=p2.Id); Product2 p3 = new Product2( Name = 'prod3', Family = 'Card Not Present'); insert p3; PricebookEntry pE3 = new PricebookEntry( Pricebook2Id=p.Id, Product2Id=p3.Id); OpportunityLineItem OLI1 = new OpportunityLineItem( OpportunityId=testOpportunity.Id, Quantity = 1, UnitPrice = 1 ); insert OLI1; testOpportunity.StageName = 'Closed/Won'; Test.startTest(); update testOpportunity; Test.stopTest(); } }
Let us know if this will help you