How to use test data factory to create apex test class in Salesforce | Create test data factory for Apex Tests Unit to code coverage for Quote and QuoteLineItem in Salesforce

523 views


Hey guys, today in this post we are going to learn about How to Create test data factory apex test class to code coverage for Quote and QuoteLineItem in Salesforce.

The @IsTest annotation Classes defined this way should only contain test methods and any methods required to support those test methods. One advantage to creating a separate class for testing is that classes defined with @IsTest don’t count against your org’s limit of 6 MB of Apex code. To know more details about Test Class, Click Here.

 

 

Final Output →

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!

 

test data factory to create apex test class -- w3web.net

 

You can download file directly from github by Click Here.

 

Other related post that would you like to learn in Salesforce

 

  • Find the below steps ▾

 

Create Apex Class Controller

Step 1:- Create Apex Class : createQuoteAndLineItemLwcCtrl.apxc

From Developer Console >> File >> New >> Apex Class

createQuoteAndLineItemLwcCtrl.apxc [Apex Class Controller]

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 
  1.   public WITH sharing class createQuoteAndLineItemLwcCtrl {
  2.     public createQuoteAndLineItemLwcCtrl() {
  3.  
  4.     }
  5.  
  6.     @AuraEnabled(cacheable=TRUE)
  7.     public static List<Opportunity> getOpportunityList(Id recId){
  8.         List<Opportunity> optList = [SELECT Id, Name, Description FROM Opportunity WHERE Id=:recId];
  9.         RETURN optList;
  10.     }
  11.  
  12.      //START Quote
  13.  
  14.   @AuraEnabled
  15.   public static String  submitOptRecord(String jsonDataStr) {
  16.  
  17.       Map<String, Object> RESULT = NEW Map<String, Object>();
  18.       String DataRespoce ='';
  19.       try {
  20.           Map<String, Object> formDataMap = (Map<String, Object>)JSON.deserializeUntyped(jsonDataStr);
  21.  
  22.           Map<String, Object> OptDataMap = (Map<String, Object>)formDataMap.get('optDataFyObj');
  23.  
  24.          // Opportunity optObj = NEW Opportunity();
  25.           Quote optObj = NEW 	Quote();
  26.           optObj.Name = getStringValueFromMap(OptDataMap, 'Name');
  27.           optObj.OpportunityId = getStringValueFromMap(OptDataMap, 'OpportunityId');
  28.           optObj.Description = getStringValueFromMap(OptDataMap, 'Description');
  29.           optObj.Pricebook2Id = getStringValueFromMap(OptDataMap, 'Pricebook2Id');
  30.           List<DATABASE.SaveResult> insertResult = DATABASE.insert(NEW List<Quote>{optObj});
  31.  
  32.           DataRespoce =JSON.serialize(insertResult); 
  33.  
  34.  
  35.       }catch(Exception ex) {
  36.  
  37.           RESULT.put('status', 500);
  38.           RESULT.put('message', 'Exception ' + ex.getMessage() + ',line' + ex.getLineNumber());
  39.       }
  40.       RETURN DataRespoce;
  41.   }
  42.  
  43.  
  44.  
  45.  
  46.   public static String getStringValueFromMap(Map<String, Object> dataMap, String fieldName) {
  47.       String VALUE;
  48.       try {
  49.           IF(dataMap.containsKey(fieldName)) {
  50.               VALUE = String.valueOf(dataMap.get(fieldName));
  51.           }
  52.  
  53.           VALUE = String.isEmpty(VALUE) ? VALUE :  String.valueOf(VALUE);
  54.       } catch(Exception ex) {
  55.           System.debug('Exception getValueFromMap : '+ ex.getMessage() + ' line ' + ex.getLineNumber());
  56.       }
  57.  
  58.       RETURN VALUE;
  59.   }
  60.  
  61.  
  62.  
  63.  
  64.  
  65.   public static DATE getDateValueFromMap(Map<String, Object> dataMap, String fieldName) {
  66.       DATE VALUE;
  67.       try {
  68.           String str;
  69.           IF(dataMap.containsKey(fieldName)) {
  70.               str = String.valueOf(dataMap.get(fieldName));
  71.           }
  72.  
  73.           VALUE = String.isEmpty(str) ? VALUE :  DATE.valueOf(str);
  74.       } catch(Exception ex) {
  75.           System.debug('Exception getIntValueFromMap : '+ ex.getMessage() + ' line ' + ex.getLineNumber());
  76.       }
  77.  
  78.       RETURN VALUE;
  79.   }
  80.  
  81.  
  82.  
  83.  
  84.  
  85.   //START Quote Line Item
  86.  
  87.  
  88.  
  89.  
  90.   @AuraEnabled
  91.   public static void saveQuoteLineItem(List<QuoteLineItem> quoteItemList){
  92.       try {           
  93.          INSERT quoteItemList;
  94.          System.debug('quoteItemList## ' + quoteItemList);
  95.       }
  96.       catch(Exception ex) {
  97.           System.debug('Exception getValueFromMap : '+ ex.getMessage() + ' line ' + ex.getLineNumber());
  98.       }
  99.  
  100.  
  101.   } 
  102.  
  103.  
  104. //END Quote Line Item
  105.  
  106.  
  107. }

 

Create Test Data Factory Controller

Step 2:- Create Apex Class : TestDataFactory.apxc

From Developer Console >> File >> New >> Apex Class

TestDataFactory.apxc [Apex Class Controller]

  1.   public class TestDataFactory {
  2.  
  3.      public static Account createAccount() {
  4. 		Account acc = NEW Account();
  5.         acc.Name='test';
  6.         acc.Description='test';
  7.         INSERT acc;
  8.         RETURN acc;
  9. 	}
  10.  
  11.     public static string jsonDataStrObj(){
  12.         String jsonStr = 
  13.         '{"invoiceList":[' +
  14.         '{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
  15.             '{"Country":"India","Type":"test","Frequency":"test"},' +
  16.             '{"Country":"India","Type":"test","Frequency":"test"}],' +
  17.                 '"invoiceNumber":1},' +
  18.         '{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
  19.             '{"Country":"India","Type":"test","Frequency":"test"},' +
  20.             '{"Country":"India","Type":"test","Frequency":"test"},' +
  21.             '{"Country":"India","Type":"test","Frequency":"test"}],"invoiceNumber":2}' +
  22.         ']}';
  23.         RETURN jsonStr;
  24.     }
  25.  
  26.  
  27.     public static Map<String, Object> createDataMap(){
  28.         opportunity opt = NEW opportunity();
  29.         opt.Name='test';
  30.         opt.StageName='Prospecting';
  31.         opt.CloseDate=system.today();
  32.         INSERT opt;
  33.  
  34.         Map<String, Object> dataMap = NEW Map<String, Object>();
  35.         dataMap.put('test1',opt);
  36.         RETURN dataMap;
  37.     }
  38.  
  39.     public static opportunity createOppt(){
  40.         Account acc = TestDataFactory.createAccount();
  41.         opportunity opt = NEW opportunity();
  42.         opt.Name='test';
  43.         opt.StageName='Prospecting';
  44.         opt.CloseDate=system.today();
  45.         opt.AccountId=acc.Id;
  46.         INSERT opt;
  47.         RETURN opt;
  48.     }
  49.  
  50.  
  51.     public static Product2 createProduct(){
  52.         Product2 p2= NEW Product2();
  53.         p2.Name= 'test';
  54.         p2.IsActive=TRUE;
  55.         p2.ProductCode='test';       
  56.         INSERT p2;
  57.         RETURN p2;
  58.     }
  59.  
  60.     public static Pricebook2 createPricebook(){
  61.         Pricebook2 p1 = NEW Pricebook2();
  62.         p1.Name='test';
  63.         p1.IsActive=TRUE;         
  64.         INSERT p1;
  65.         RETURN p1;
  66.     }
  67.  
  68.  
  69.     public static PricebookEntry createPricebookEntry(){
  70.         Id priceId = Test.getStandardPricebookId();
  71.          Pricebook2 p1 = TestDataFactory.createPricebook();
  72.          Product2 p2 = TestDataFactory.createProduct();
  73.  
  74.         PricebookEntry priceBkEntry = NEW PricebookEntry();
  75.         priceBkEntry.UseStandardPrice=TRUE;
  76.         priceBkEntry.Pricebook2Id= priceId;
  77.         //priceBkEntry.Pricebook2Id=p1.Id;        
  78.         priceBkEntry.Product2Id=p2.id;
  79.         priceBkEntry.UnitPrice=40446;
  80.         priceBkEntry.UseStandardPrice=FALSE;
  81.         priceBkEntry.IsActive=TRUE;
  82.         //NEW PricebookEntry (Product2Id=p2.id,Pricebook2Id=Test.getStandardPricebookId(),UnitPrice=40446, UseStandardPrice=TRUE, isActive=TRUE);
  83.         INSERT priceBkEntry;
  84.         RETURN priceBkEntry;
  85.     }
  86.  
  87.  
  88.     public static Quote createQuote(){
  89.         Id priceId = Test.getStandardPricebookId();
  90.         Opportunity opt = TestDataFactory.createOppt();
  91.         Pricebook2 p1= TestDataFactory.createPricebook();        
  92.         Quote q2 = NEW Quote();
  93.         q2.Email='test@test.com'; 
  94.         q2.Name='test'; 
  95.         q2.OpportunityId=opt.Id;     
  96.         //q2.Pricebook2Id=p1.Id;
  97.         q2.Pricebook2Id=priceId; 
  98.         INSERT q2;
  99.         RETURN q2;
  100.     }
  101.  
  102.     public static List<QuoteLineItem> createQuoteLineItem(){
  103.          Id priceId = Test.getStandardPricebookId();
  104.         List<QuoteLineItem> quoteItemLst = NEW List<QuoteLineItem>();
  105.         Quote q2= TestDataFactory.createQuote();   
  106.         PricebookEntry priceBkEntry= TestDataFactory.createPricebookEntry(); 
  107.         Product2 p2= TestDataFactory.createProduct(); 
  108.  
  109.         QuoteLineItem qitm = NEW QuoteLineItem();        
  110.         qitm.Description='test';
  111.         qitm.QuoteId=q2.Id;
  112.         qitm.PricebookEntryId=priceBkEntry.Id;
  113.         qitm.Quantity=1.0;
  114.         qitm.UnitPrice=1.0;
  115.         qitm.Product2Id=p2.Id;
  116.         INSERT qitm;
  117.         quoteItemLst.add(qitm);
  118.         RETURN quoteItemLst;
  119.     }
  120.  
  121. }

 

Create Apex Test Class

Step 3:- Create Apex Class : createQuoteAndLineItemLwcCtrlFactoryTest.apxc

From Developer Console >> File >> New >> Apex Class

createQuoteAndLineItemLwcCtrlFactoryTest.apxc [Apex Class Controller]

  1.   @isTest
  2. public class createQuoteAndLineItemLwcCtrlFactoryTest {
  3.  
  4.     static testMethod void getOpportunityListTest(){
  5.          opportunity optObj = TestDataFactory.createOppt(); 
  6.  
  7.          test.startTest();
  8.          createQuoteAndLineItemLwcCtrl.getOpportunityList(optObj.Id);
  9.          test.stopTest();
  10.     }
  11.  
  12.  
  13.     static testMethod void submitOptRecordTest(){
  14.         String jsonDataStr = TestDataFactory.jsonDataStrObj();
  15.  
  16.         test.startTest();
  17.         createQuoteAndLineItemLwcCtrl.submitOptRecord(jsonDataStr);
  18.         test.stopTest();
  19.     }
  20.  
  21.     static testMethod void getDateValueFromMapTest(){
  22.         Map<String, Object> dataMap = TestDataFactory.createDataMap();
  23.  
  24.         test.startTest();
  25.         createQuoteAndLineItemLwcCtrl.getDateValueFromMap(dataMap,'test');
  26.         test.stopTest();        
  27.     }
  28.  
  29.  
  30.     static testMethod void saveQuoteLineItemTest(){
  31.         //Id priceId = Test.getStandardPricebookId();
  32.         List<QuoteLineItem> quotItmLst = TestDataFactory.createQuoteLineItem();
  33.         test.startTest();
  34.         createQuoteAndLineItemLwcCtrl.saveQuoteLineItem(quotItmLst);
  35.         test.stopTest();
  36.     }
  37.  
  38. }

 

Further post that would you like to learn in Salesforce

 

 

FAQ (Frequently Asked Questions)

What is Apex test class in Salesforce?

Test classes are written in Apex and are used to verify that the code written by developers works as intended before it is deployed to a production environment. Test classes are not counted in code coverage before they get deployed by the Salesforce Admin in final production.

What is Apex Test Suite in Salesforce?

A test suite is a collection of Apex test classes that you run together. For example, create a suite of tests that you run every time you prepare for a deployment or Salesforce releases a new version. Set up a test suite in the Developer Console to define a set of test classes that you execute together regularly.

What is test data for apex tests?

est data is the transient data that is not committed to the database and is created by each test class to test the Apex code functionality for which it is created. The use of this transient test data makes it easy to test the functionality of other Apex classes and triggers.

Related Topics | You May Also Like

 
Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 
  

Our Free Courses →

👉 Get Free Course →

📌 Salesforce Administrators

📌 Salesforce Lightning Flow Builder

📌 Salesforce Record Trigger Flow Builder

👉 Get Free Course →

📌 Aura Lightning Framework

📌 Lightning Web Component (LWC)

📌 Rest APIs Integration



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net

Leave a Comment