Salesforce Apex Testing

Apex Testing

  • Apex Testing is the process that helps you to create relevent test data in the test classes and run them in salesforce.
  • Apex provides a testing framework that allows you to write unit tests, run your test and run check the code coverage results.
  • Atleast 75% of your code must be covered by all the unit tests.
  • Every trigger and classes must have the test coverage.
  • System.debug, test method and test classes is not counted as a part of the code coverage.

We need to test for the:

  • Positive Behaviour: The input you are giving in the test class based on class is returning expected output or not.
  • Negative Behaviour: returning unexpected output.
  • Restrcited User: Check that a user whose access to certain objects or records is restricted.

Purpose of Apex Testing

  • All the code you have written down work as per specification.
  • To build a long lasting product that your customer can rely on.
  • If the apex code is not properly tested than it can't be deployed into the production.

What are unit test and how to write them?

  • Unit test are class methods that verfify wheather a particular piece of code working properly or not.
  • Unit test methods does'nt take arguments,commit no data to the database, send no email.
  • Create a different test methods to test different functionalities.
  • Use @ istest notation to define test class and method.
  • Unit test method are contain only in the test classes.
  • Always defined as static methods.

System Defined Methods Used In Apex Class

  • These are used when testing governor limits or we can say that existing test scenerios with the largest data.
  • Governor limits are reset when the Test.startTest appears and the code between Test.startTest and Test.stopTest executes in a fresh set of governor limits.

startTest: Tells the begining of test code.
stopTest: Tells the end of test code.

Test Setup Methods

  • These are Special methods which are used to create test data that becomes accessible to the whole Test Class.
  • These methods use @ TestSetup annotation.

@ isTest
private class CommonTestSetup {
 @ testSetup static void setup() {
 // Create common test accounts
 List<Account> testAccts = new List<Account>();
 for(Integer i=0;i<2;i++) {
 testAccts.add(new Account(Name = 'TestAcct'+i));
 }
 insert testAccts;
 }
 @ isTest static void testMethod1() {
 // Get the first test account by using a SOQL query
 Account acct = [SELECT Id FROM Account WHERE Name='TestAcct0' LIMIT 1];
 // Modify first account
 acct.Phone = '555-1212';
 // This update is local to this test method only.
 update acct;
 // Delete second account
 Account acct2 = [SELECT Id FROM Account WHERE Name='TestAcct1' LIMIT 1];
 // This deletion is local to this test method only.    
delete acct2;
 }

@ isTest(SeeAllData=true)

  • It Will Open up the data access to records in organisation.
  • It is apply to only query the data it does not apply to record creation, changes or deletion.

@ isTest(SeeAllData=true)
public class DataaccessOnAccount{
    static testmethod void getAccountTest(){
test.startTest();
//It is Querying the existing account from the salesforc organisation.

Account a = [select Id, Name from Account Where Name='ABC' Limit 1];
system.debug('To confirm the Id '+ Id);
system.assert(a!=null);
}
    }
//using the same id you can change the data by clone(creating the new test account the one which we queried ago)    
//Remember this is in the test data this will not effect the data in the organisation.

Account newaccount = a. clone();
newaccount.name = 'abc1';
insert newaccount;

Account testaccount2 = [select Id, Name from Account where Name = 'abc1' limit 1];
system.assert(testaccount2!=null)
test.stopTest();

}    
    }

Examples

Example:1


public class DiscountPriceHelperClass {
    public static void discount(List<Library__c> Library){
         {
        for(Library__c eb: library)
            eb.Price__C*=0.9;
    }
    }

@ isTest
private class dicounttestclass{
@ isTest            //TestMethod = testmethod or you can use @ isTest

//Inside a private test class we can't use the public method 

Static Void discountpricetest(){

test.startTest();
// Step 1: Initialise the class and create a new sample book in library object

Library__c L = new library__c();
L.name = 'mybook1';
L.price = 1000;
Insert L;

// Step 2: SOQL
//Whatever we created above now we are getting it from the database 

List<library__c> booklist = [Select Id, Price__c from Library__c where Id=:B.Id];

//Step 3: Compare the price expected in the database
//I wanted to verify that logic is applied or not in order to check that we have (System. Assert)

//System.assertEquals(expected, actualvalue)
//Expected ==> what we want , actual value ==> what we are getting as an input 

System.assertEquals(900, booklist[0].Price__c);
test.stopTest();
}
}

Example:2


public class Question1OddNumber {
    public void Myanswer1()
    {
       List<Integer> numList=new List<Integer>();
        integer sum=0;

       for(Integer j=1;j<=20;j=j+2){
                numList.add(j);
             sum=sum+j;
            }
         System.debug(numList);  
        system.debug(sum);
     }
}


@istest
public class Question1OddNumberTest {
    public static testmethod void testcoverageforoddnumber(){
        test.startTest();
Question1OddNumber odi = new Question1OddNumber();
        odi.Myanswer1();

        test.stopTest();
    }
}

Points To Remember

  • Classes and methods defined as @ istest can either be public or private.
  • If class members are private they are not visible to test class to access them you can use @ testvisible notation.
  • The system. runAs method enables you to write test methods that change the user context to an existing user or a new user so that the user’s record sharing is enforced.

Questionnaire

Suppose i have a test class in which i have created a testSetup method in which i am creating a contact record. Let say i have two test method inside my test class which is accessing this contact record. If i access this contact record in testmethod1() and made a update to the contact record from testSetup method and now i am accessing this contact in testmethod2(), so will i get the updated contact record or the original unmodified contact record in testmethod2()?

testMethod2() will gets access to the original unmodified state of record, this is because changes are rolled back after each test method finishes execution.

If the test class is having access to organization data using @ isTest(SeeAllData=true) annotation, will the test class be able to support @ testSetup method?

@ testSetup method are not supported in this case.

What is @ isTest annotation? When you will use it?

When you define method or class using @ isTest annotation then it only contains code used for testing your application. Test classes should be public or private only. Test class doesn't count against your organization limit of 3 MB for all Apex code.

Conclusion

Apex provides a testing framework that allows you to write unit tests, run your test and run check the code coverage results. Atleast 75% of your code must be covered by all the unit tests.

❤️ By Pradhumn