Unit Testin in Apex

Episode 6 – Unit Testing in Apex

Testing is in imperative aspect of the software development life-cycle. In this episode we will learn about writing unit test code to verify the implemented business logic using Apex. Join us as you embark on this wonderful journey to become a champion Salesforce developer.

Agenda

  • What are Unit Tests?
  • Why are Unit Tests needed?
  • Anatomy of a Unit Test Code
  • Running Unit Tests and understanding code coverage
  • TestDataFactory
  • Q & A

Most importantly don’t break a leg if you are overwhelmed with the pace of the live sessions. All Apex Hours for Student sessions will be recorded and will be available on our YouTube channel.

Please register here and follow our ApexHours website to get more notification.

Here is some keynote of session

What are Unit tests

  • In other word, we can say that unit tests are the test performed by the developers to ensure that functionality is working as expected considering Both positive & Negative tests.
  • Unit tests are also used in long-term development project to ensure that project is running error-free & smooth.

Why Unit tests are needed

  • Validate Desired Behavior
  • Reduce the bug Cost
  • Perform Bulk tests
  • 75% Code coverage for Production deployment

What to Test

  • Apex Trigger
  • Apex Class – Handler/Helper, WebService, Apex REST, SOAP
  • VF Page
  • Apex Batch/Queueable/Future Method
  • Custom Controller

I have written unit test, now what ?

Once you have created/developed the Unit test for your Apex Class or Apex Trigger. Now, it’s time to run the tests
1) Using Developer Console
2) Using Salesforce Interface

TestSetup method in Test Class

  • Use testsetup method in test class to create the data at once and use it across all the test methods in the same class.
  • Increase performance of the test class.
  • Testsetup methods executes first before any testmethod executes in test class.
  • If any test method, modified the record like field update or deletion, these kinds of changes rolled back after finish of the testmethod and next method gets the original unmodified record.
  • If a class contains testSetup method then you can not use SeeAllData=true in test class
  • Only one setup method can be used in a test class.
  • If there is any error in setup method. Entire class will be failed
TestSetup method in Test Class
TestSetup method in Test Class

Write effective Unit tests

To write an effective test cases, a developer needs to ensure to include the below points into the test class

  • Use Test.startTest & Test.stopTest into each test method
  • Use @isTest annotation for each method instead of using testMethod
  • Develop cases for all scenarios if there are multiple if conditions
  • Use System.assert, System.assertEquals to validate the result.
  • Always test your Class/Trigger for at least 200 records
  • Create the required test data in test class.
  • Always use ( seeAllData = false ) at class or method level
  • Etc.

Important thing to learn

Important thing to learn

TestDataFactory class Unit tests

TestDataFactory is an Apex Class which is used to generate the Test Data in a Class and the data can be used across multiple test classes.

This class is useful when multiple classes are using same data and avoid duplicate code, increase reusability & increase performance of the test case

Recording

Writing Test Classes in Salesforce

Write effective Unit tests/ test Classes

Episode 6 will be presented by Amit Singh on Feb 17, 2020 at 6 PM Indian Standard Time.

Further Learning

Get Started with Apex Unit Test

Best Practice for Test classes | Sample Test class

Apex Unit Tests

Assignment

Complete below assignment to win $1000 Salesforce Voucher. Click here for rule.

1.Create Test class for the Assignment 5. Make sure that you have applied the following points
•To generate the data use Test.LoadData method in TestDataFactory class
•TestDataFactory Class to prepare the data
•Use testSetup method in Test Class
•Must have both positive & negative testing
•Testing must be done for at-least 50 records
•Code coverage must be 95%

Don’t forget to register for our next session on Asynchronous Processing in Apex. Check this post for all other session detail.

Please note that we have limit of 500 attendees that can join the online sessions. However, recording will be posted on our YouTube channel. Make sure to subscribe our YouTube channel to get notification for video upload.

So, learn at your pace and free will and ace your journey to Salesforce!

15,792 total views, 39 views today

16 thoughts on “Episode 6 – Unit Testing in Apex”

  1. You guys are amazing – thanks for all the knowledge you’re providing.

    Can we get slides of all the sessions?

    Reply
  2. Code for Assignment Day 6
    ——————————–

    @isTest
    public class TestDataFactory {
    public static Account createAccount(Boolean doInsert) {
    Account account = new Account();
    account.Name = ‘Test Account’;
    if(doInsert){
    insert account;
    }
    return account;

    }
    public static Invoice__c createInvoices(Boolean doInsert, Id accountId){
    Invoice__c invoice = new Invoice__c();
    invoice.Account__c = accountId;
    invoice.Status__c = ‘Pending’;
    invoice.Invoice_Name__c = ‘Test Invoice’;
    invoice.Invoice_Date__c = Date.parse(system.today().format());

    if(doInsert) {
    insert invoice;
    }
    return invoice;
    }

    public static List createInvoiceItems(Boolean doInsert, Id invoiceId) {
    List listItems = new List();
    for(Integer i=1;i<=50;i++) {
    Invoice_Line_Item__c item = new Invoice_Line_Item__c();
    item.Invoice__c = invoiceId;
    item.Invoice_Line_Item_Name__c = 'Test Invoice Item ' + i;
    item.Price__c = 2.0;
    listItems.add(item);
    }
    if(doInsert) {
    insert listItems;
    }
    return listItems;
    }
    }

    —————————————————–

    @isTest
    public class InvoiceAmountUpdateTest {

    @testSetup
    public static void setUp(){
    Account acc = TestDataFactory.createAccount(true);
    Invoice__c inv = TestDataFactory.createInvoices(true,acc.Id);
    TestDataFactory.createInvoiceItems(true,inv.Id);
    }

    @isTest
    public static void myUnitTest(){
    Account account = [select Name from Account where name='Test Account'];
    System.assertEquals(account.Name , 'Test Account');
    System.assertNotEquals(null, account);

    Invoice__c invoice = [select Total_Amount__c from Invoice__c where Invoice_Name__c = 'Test Invoice'];
    System.assertEquals(invoice.Total_Amount__c, 100);
    System.assertNotEquals(0, invoice.Total_Amount__c);
    }

    @isTest
    public static void myUnitTest1(){
    List listItemsDelete = new List();
    List listItems = [select Id from Invoice_Line_Item__c limit 25];
    for(Integer i=0;i<listItems.size();i++) {
    Invoice_Line_Item__c item = listItems.get(i);
    listItemsDelete.add(item);
    }
    delete listItemsDelete;

    System.assert(listItemsDelete.size() == 25, '25 Invoice Line Items has been tested after deleted');
    }
    }

    Reply
  3. In this video, before starting the test data factory the trainer said “don’t worry about the code , the code will be available in apexhours.com “. but tell me where is the code in this site.

    Reply

Leave a Comment