Tag: Assert Statements

  • What is a Test class in Salesforce? | The Ultimate Guide

    What is a Test class in Salesforce? | The Ultimate Guide

    Testing is an important part of SDLC. So, before deploying our code to the production environment, Salesforce requires at least 75% of your code to be covered by our test classes which. To make sure that our code doesn’t break in any situation in Production, Salesforce has done this. Now we’ll see how we write the test class with examples in Salesforce. 

    Things to Keep in Mind while writing a Test Class

    1. At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully. But this should not be our focus. We should aim for 100% code coverage, which ensures that you cover each positive and negative use case of your code to cover and test each and every branch of your code. 
    2. System.debug is not counted as part of Apex code coverage. 
    3. Test classes are not counted as part of the Apex code limit. So, we do not have to worry about writing long test classes with more methods just to make sure that all your code branches are covered. 
    4. The trigger you are trying to deploy should have at least 1% coverage, but yes overall coverage of your production org after getting your code deployed should be 75%, otherwise, you won’t be able to deploy your code. 
    5. The class can be deployed on 0% coverage as well, but as I told you in the last point, the overall coverage of your production org after getting your code deployed should be 75%, otherwise Salesforce won’t let you deploy your code. 

    dont miss out iconDon’t forget to check out: Get Started with Salesforce Apex Test Class | The Developer Guide

    The Key Points

    1. We have to start our class with @isTest annotation, then only Salesforce will consider this class as a test class. 
    2. Keep your class Private, and the best practice is to name your test class as your original Class or trigger Name + ‘Test’. 
    3. Methods of test class have to be static, and void, and the testMethod keyword has to be used. 
    4. Prepare test data that needs to be existing before your actual test runs. are multiple techniques of creating test data now a days, for example, setup method, static resources, etc. We should use Test.startTest() and Test.stopTest() to make sure that the actual testing of your code happens with the fresh set of governer limits. These methods help you to reset your governor limits just before your actual code of testing gets executed. 
    5. Once your test code runs between Test.startTest() and Test.stopTest(), you must use assert statements to test whether your actual code is executing correctly and giving the results as expected. In our case, we are testing whether the book’s price has been set to 90 or not. If this assert statement returns false, then your test class will fail, and will let you know, that something is not correct in your code, and you need to fix your original code. 
    6. Because we are testing a simple trigger, we could not show the testing using negative use cases, but in an ideal world, you should write multiple methods in your test class, a few should test your positive use cases, and others should test your negative test cases.

    dont miss out iconCheck out another amazing blog by Rupesh here: How to Display Images from File Tab to Salesforce App by using Aura Component?

  • How to Write a Test Class in Salesforce? The Salesforce Developer Guide

    How to Write a Test Class in Salesforce? The Salesforce Developer Guide

    In any development, testing is a very important step as it tells us about how good the development has been done and for that we have Test Classes in Apex. Before getting to know how to write a test class, let’s first understand what exactly a test class is. 

    What is a Test Class?

    Test classes are the code snippets which test the functionality of your Apex code. 

    • “@isTest” annotation is used for defining a class or a method as “Test Class or Test Method.”  
    • Previously, a “testMethod” keyword was used to define a method as test method. But now it is deprecated by Salesforce. 
    • You aren’t required to add any access modifier like public, private etc. For test method as it will be accessible to the whole test class. 
    • Test Classes don’t have access to the existing data of your Org, by default. So, you need to create test data within the test class. 
    • Test classes and their Test methods are not counted as a part of Apex code limit 
    • Test Class must cover at least 75% of the code. This limit is set by Salesforce, if you have not fulfilled the criteria then your code can’t be deployed.  

    Test Method Syntax 

    @isTest static void nameOfTestMethod() {   
        // code  
    }

    This is what a test class looks like…

    @isTest 
    public class FirstTestClass { 
        @isTest static void firstTestMethod() { 
            // code 
        }
    }

    dont miss out iconDon’t forget to check out: 10 Example Future Method with Test Class | Asynchronous Apex | Salesforce Development Training Video

    How Can I Create One?

    1. Go to Developer Console > File > New > Apex Class. 
    2. Write your test class here > Save 
    3. Click on “Run Test” button. 
    4. See if your test class ran successfully or not by clicking on the “Tests” tab at the bottom. 
    5. A “green tick” symbol indicates the successful status of the test class and a “red cross” symbol indicates failed test class. 
    6. If your test class ran successfully then go to your main class and see the code coverage by clicking on the Code Coverage button on the top left. You can also click on the arrow icon to see the code coverage method-wise. 
    7. Click on the red cross symbol to view why test class failed and try to debug. 

    Write your 1st Test Class

    Let’s write a test class for a trigger that deletes any related account to an opportunity whenever the opportunity gets deleted. 

    OpportunityDeletion Trigger:

    As a best practice, create only one trigger per object. So here is the trigger which executes on after delete event.   

    trigger OpportunityDeletion on Opportunity (after delete) { 
        if(trigger.isAfter){ 
            if(trigger.isDelete){ 
                OpportunityDeletionHandler.onAfterDelete(trigger.old);             
            } 
        } 
    }

    OpportunityDeletion Handler Class:

    This is the handler class for the above trigger in which the main logic is written.  

    public class OpportunityDeletionHandler { 
        public static void onAfterDelete(List<Opportunity> oppList){ 
            Set<Id> accountToBeDeleted = new Set<Id>();          
            for(Opportunity o : oppList){            
                accountToBeDeleted.add(o.AccountId); 
            }          
            List<Account> acc = [select Id from Account where id in: accountToBeDeleted]; 
            if(!acc.isEmpty()){             
                delete acc;  
            }    
        } 
    }

    OpportunityDeletion Test Class: 

    @isTest public class OpportunityDeletionTest { 
        @isTest static void testOppDeletion(){ 
            Account acc=new Account();		//Creating test data 
            acc.Name='testAccount';			//Creating a test Account record 
            insert acc;          
            Opportunity opp= new Opportunity();	//Creating a test Opportunity record 
            opp.Name='testOpp'; 
            opp.AccountId=acc.Id; 
            opp.CloseDate = system.today(); 
            opp.StageName = 'Prospecting'; 
            insert opp;          
            Test.startTest();	// Provides new set of governor limits for testing actual code  
            delete opp;	 
            Test.stopTest();	// Return to the previous governor limits			 
        } 
    }

    Good job! you have written your 1st test class successfully.  

    dont miss out iconCheck out another amazing blog by Tanya here: What is Salesforce CPQ – Why Does Every Business Need it?

    Best Practices to write an efficient Test Class:

    1. If you have many methods in test class, use @testSetup method and create all records once within this method. Whenever you need data, just query it in the test methods and you’ll not need to create data all over again! 
    2. Don’t use hardcoded IDs anywhere in the test class, else it will break in the production org. 
    3. Take care of Governor Limits by using Test.startTest() and Test.stopTest() methods. 
    4. Always aim for 100% and cover Tests for Positive Cases, Negative Cases, Single records, Bulk Records and for Restricted Users. 
    5. Test for Exception. Create data that will throw exceptions so that if any exception occurs at Production org, error messages can be displayed for the same.  
    6. Use assert statements for the positive and negative cases in the test methods. 

    With this, we reached the end of this blog. Hope it helped you!