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 ?

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 :
    public static string opportunityProductCreation(Id oppId, List<OpportunityLineItemWrapper> oliData)
        Id oppRecordId;
        string error=null;
        try {
            if (oppId == null) {
                return null;
            }else {
                oppRecordId = oppId;

                error ='Creation of Opportunity products is failed due to empty data';
                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) {

            //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'])

            for(OpportunityLineItemWrapper lwrp:oliData)
                OpportunityLineItem li = new OpportunityLineItem();            
                li.OpportunityId = oppRecordId; 
                li.PricebookEntryId = prodPbeMap.get(lwrp.selectedProductId);
                //check for competitor
                    li.CompetitorName__c = lwrp.competitor;                    
                //check for resalePrice
                    li.ResalePrice__c = decimal.valueOf(lwrp.resalePrice);                    
                //check for targetCost
                    li.TargetPrice1__c = decimal.valueOf(lwrp.targetCost);
                //check for orderQuantity
                    li.Quantity = decimal.valueOf(lwrp.orderQuantity);
                //check for mPrice
                    li.UnitPrice = decimal.valueOf(lwrp.mPrice);
                    li.Price1__c = decimal.valueOf(lwrp.mPrice);
                    li.UnitPrice = 0;
                //check for perUnit
                    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;

             // 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((String.isEmpty(error)) && (lineItemFinalList.size()>0))
                insert lineItemFinalList;
                return 'SUCCESS';
            return error;

        } catch (Exception e) {
            system.debug('Error Msg-- ' + e.getMessage() + 'Error Line No-- ' + e.getLineNumber());
            throw new AuraHandledException(e.getMessage());

PriyaPriya (Salesforce Developers) 
Hey Ragnar,

Please learn to write the test class from this salesforce official site Trailhead (

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.
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 =,
            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(
            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>{
        opportunityProductCreation.opportunityProductCreation(opp.Id, oliwrapperList);
        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?