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
Ragnar Lothbrok 7Ragnar Lothbrok 7 

How to start / write the Apex test class ?

Hello,
I am new to Apex coding, and also I am not comfortable to write test class. Can anyone help me to write the test class for this Apex class method. And also if you can suggest me how to start on writing test class so that i can also create one.
Apex Class Method :
@AuraEnabled
    public static string opportunityProductCreation(Id oppId, List<OpportunityLineItemWrapper> oliData)
    {
        //Start
        Id oppRecordId;
        string error=null;
        try {
            if (oppId == null) {
                return null;
            }else {
                oppRecordId = oppId;
            }         

            if(oliData.size()==0)
            {
                error ='Creation of Opportunity products is failed due to empty data';
            }
            
            if(oliData.size()>100)
            {
                error = 'Please make sure to upload not more than 100 records at a time.';
            }
            
            List<OpportunityLineItem> lineItemInsertList = new List<OpportunityLineItem>();

            //set of map to store productId that needs to be inserted
            Set<id> prdIdset = new Set<id>();        
            for (OpportunityLineItemWrapper olwrp : oliData) {
                prdIdset.add(olwrp.selectedProductId);
            }

            //map to store the productId as key with pricebookentryId as value
            Map<string,string> prodPbeMap = new Map<string,string>();
            for(PricebookEntry pe:[select id,IsActive,CurrencyIsoCode,Product2Id,Pricebook2Id,
                                Pricebook2.IsStandard,Name from PricebookEntry 
                                where Product2Id IN:prdIdset and Pricebook2.IsStandard=true and CurrencyIsoCode='USD'])
            {
                prodPbeMap.put(pe.Product2Id,pe.id);
            }

            for(OpportunityLineItemWrapper lwrp:oliData)
            {
                OpportunityLineItem li = new OpportunityLineItem();            
                li.OpportunityId = oppRecordId; 
                li.PricebookEntryId = prodPbeMap.get(lwrp.selectedProductId);
                
                //check for competitor
                if(lwrp.competitor!=null){                  
                    li.CompetitorName__c = lwrp.competitor;                    
                }
                //check for resalePrice
                if(lwrp.resalePrice!=null){
                    li.ResalePrice__c = decimal.valueOf(lwrp.resalePrice);                    
                }
                //check for targetCost
                if(lwrp.targetCost!=null){
                    li.TargetPrice1__c = decimal.valueOf(lwrp.targetCost);
                }
                //check for orderQuantity
                if(lwrp.orderQuantity!=null){
                    li.Quantity = decimal.valueOf(lwrp.orderQuantity);
                }
                //check for mPrice
                if(lwrp.mPrice!=null)
                {
                    li.UnitPrice = decimal.valueOf(lwrp.mPrice);
                    li.Price1__c = decimal.valueOf(lwrp.mPrice);
                }
                if(lwrp.mPrice==null)
                {
                    li.UnitPrice = 0;
                }
                //check for perUnit
                if(lwrp.perUnit!=null){
                    li.PriceUnit__c= decimal.valueOf(lwrp.perUnit);                    
                } 

                //This is for temporary purose - default the currency as user currency
                string userCurr = UserInfo.getDefaultCurrency();                
                li.PriceCurrency1__c = userCurr;

                lineItemInsertList.add(li); 
            }
             // Check for duplicate Pricebook Entry list and avoid duplicate Line item creation
            Set<string> pbEntryIdSet= new Set<string>();
            List<OpportunityLineItem> lineItemFinalList = new List<OpportunityLineItem>();
            for(OpportunityLineItem ol:lineItemInsertList)
            {
                if(pbEntryIdSet.add(ol.PricebookEntryId))
                {
                    lineItemFinalList.add(ol);
                }
            }

            system.debug('--lineItemInsertList--'+lineItemInsertList);
            system.debug('--lineItemFinalList--'+lineItemFinalList);
            
            if((String.isEmpty(error)) && (lineItemFinalList.size()>0))
            {            
                insert lineItemFinalList;
                error='SUCCESS';
                return 'SUCCESS';
            }
            
            return error;

        } catch (Exception e) {
            system.debug('Error Msg-- ' + e.getMessage() + 'Error Line No-- ' + e.getLineNumber());
            SC_ExceptionLogHandler.createExceptionLog(e,'PartsComponentCls');
            throw new AuraHandledException(e.getMessage());
        }
        //End
    }

Thanks.
PriyaPriya (Salesforce Developers) 
Hey Ragnar,

Please learn to write the test class from this salesforce official site Trailhead (https://trailhead.salesforce.com/en/content/learn/modules/apex_testing/apex_testing_intro)
 

Kindly mark it as the best answer if it works for you.

 

Thanks & Regards,

Priya Ranjan


 
Abdul KhatriAbdul Khatri
Hi Ragner,

Please use the below code for your converage. Try to also read through what Priya shared. This code will help you along with your reading.

You may or may not need to tweak how your wrapper class look like, since you didn't shared. I made mine based on how it is used in the code you shared. it gave me 87% code coverage.
 
@isTest
public class opportunityProductCreationTest {

    
    //setup is a special method which is use to prep your data once to be use by multiple testmethods
    @testSetup static void setup() {
        
        Account testAccount = new Account (Name = 'Test Account');
        insert testAccount;
        
        Opportunity opportunity = new Opportunity(
            Name = 'Test Opportunity',
            AccountId = testAccount.Id,
            CloseDate = Date.today(),
            StageName = 'Prospecting'
        );
        insert opportunity;
        
        Product2 product = new Product2 (
        	Name = 'Test Product',
            IsActive = true
        );
        insert product;
        
        //Instantiate the Pricebook2 record with StandardPricebookId
        Pricebook2 standardPricebook = new Pricebook2(
            Id = Test.getStandardPricebookId(),
            IsActive = true
        );        
        //Execute an update DML on the Pricebook2 record, to make IsStandard to true
        Update standardPricebook;        
            
        PricebookEntry priceBookEntry = new PricebookEntry(
            Pricebook2Id=standardPricebook.Id,
            Product2Id = product.Id,
            UnitPrice = 10.0,
            IsActive = true
        );
        insert priceBookEntry;
    }
    
    @isTest static void testopportunityProductCreation() {
       
        Opportunity opp = [SELECT Id FROM Opportunity LIMIT 1];
        Product2 product = [SELECT Id FROM Product2 LIMIT 1];
        
        Id prdIdset = [SELECT Id FROM Product2 LIMIT 1].Id;
        
        OpportunityLineItemWrapper oliwrapper = new OpportunityLineItemWrapper();
        oliwrapper.selectedProductId = product.Id;
        oliwrapper.resalePrice = '10.00';
        oliwrapper.targetCost = '20.00';
        oliwrapper.mPrice = '30.00';
        oliwrapper.competitor = 'Test Competitor';
        oliwrapper.orderQuantity = '100.00';
        oliwrapper.perUnit = '5.00';
        
        List<OpportunityLineItemWrapper> oliwrapperList = new List<OpportunityLineItemWrapper>{
            
            oliwrapper
        };
            
        Test.startTest();
        opportunityProductCreation.opportunityProductCreation(opp.Id, oliwrapperList);
        Test.stopTest();
        
        OpportunityLineItem oli = [SELECT CompetitorName__c, ResalePrice__c
                                   			, TargetPrice1__c, Quantity, UnitPrice
                                   			, Price1__c, PriceUnit__c, PriceCurrency1__c
                                  	FROM OpportunityLineItem
                                  	WHERE OpportunityId = :opp.Id];
        
        system.assert(oli.CompetitorName__c == oliwrapper.competitor);
        system.assert(oli.ResalePrice__c == Decimal.valueOf(oliwrapper.resalePrice));
        system.assert(oli.TargetPrice1__c == Decimal.valueOf(oliwrapper.targetCost));
        system.assert(oli.Quantity == Decimal.valueOf(oliwrapper.orderQuantity));
        system.assert(oli.Price1__c == Decimal.valueOf(oliwrapper.mPrice));
        system.assert(oli.PriceUnit__c == Decimal.valueOf(oliwrapper.perUnit));
        system.assert(oli.UnitPrice == Decimal.valueOf(oliwrapper.mPrice));
        
    }    
    
}

 
Abdul KhatriAbdul Khatri
Hi Ragner,

Was the test class helpful?

Regards