How to write test class in Salesforce & what is the benefit of creating test class in Salesforce:
What is the Apex Unit Test:
The Apex testing framework enables you to write and execute tests for your Apex classes and triggers on the Lightning Platform. Apex unit tests ensure high quality for your Apex code and let you meet the requirements for deploying Apex. Testing is the key to successful long-term development and is a critical component of the development process.
Apex code can only be written in a sandbox environment or a Developer org, not in production. Apex code can be deployed to a production org from a sandbox. In addition to being critical for quality assurance, Apex unit tests are also requirements for deploying and distributing Apex.
Benefits of Apex unit tests.
- Ensuring that your Apex classes and triggers work as expected
- Having a suite of regression tests that can be rerun every time classes and triggers are updated to ensure that future updates you make to your app don’t break existing functionality
- Meeting the code coverage requirements for deploying Apex to production or distributing Apex to customers via packages
- High-quality apps delivered to the production org, which makes production users more productive
- High-quality apps delivered to package subscribers, which increase your customer’s trust
Code Coverage Requirement for Deployment:
At least 75% of Apex code must be covered by tests, and all those tests must pass. In addition, each trigger must have some coverage. Also include positive and negative test cases, and bulk and single-record processing.
Test Method Syntax
@isTest static void testName() {
// code_block
}
Test methods must be defined in test classes, which are classes annotated with @isTest
. Definition of a test class with one test method.
Test Class Syntax
@isTest
private class MyTestClass {
@isTest static void myTest() {
// code_block
}
}
Test classes can be either private or public. If you’re using a test class for unit testing only, declare it as private. Public test classes are typically used for test data factory classes.
How to Create a New Test Class:
- In the Developer Console, click File | New | Apex Class, and enter
TestClass
Name for the class name, and then click OK.
@isTest
private class TestClassName {
@isTest static void testWarmTemp() {
//Write Code Here
}
@isTest static void testFreezingPoint() {
//Write Code Here
}
@isTest static void testBoilingPoint() {
//Write Code Here
}
@isTest static void testNegativeTemp() {
//Write Code Here
}
}
How to Run Test Class :
- In the Developer Console, click Test | New Run.
- Under Test Classes, click TestClassName.
- To add all the test methods in the
TestClassName
class to the test run, click Add Selected. - Click Run.
Some Conditions when Failing the Test Class:
- if the assertion fails then fails the test class and also shows an error in the test class.
- if updation fails then fails the test class and also shows an error in the test class.
- if anything data is missing then fails the test class and also shows an error in the test class.
- if any test method fails in the test class then it will show like this, check this image
Increase Your Code Coverage:
When writing tests, try to achieve the highest code coverage possible. Don’t just aim for 75% coverage, which is the lowest coverage that the Lightning Platform requires for deployments and packages. The more test cases that your tests cover.
After you write test methods for all your class methods, code coverage is not at 100%. One common cause is not covering all data values for conditional code execution.
To cover the code coverage you need to write all the conditions according to the Condition and also you need to write the system.assert Condition to check whether the right value is coming or not after running the test class.
Best Practice to run the Test Class in between the Test.StartTest() and Test.StopTest.
Test Methods in Test Class :
The following are methods for Tests. All methods are static.
- calculatePermissionSetGroup(psgIds)
Calculates aggregate permissions in specified permission set groups for testing. - calculatePermissionSetGroup(psgId)
Calculates aggregate permissions in a specified permission set group for testing. - clearApexPageMessages()
Clear the messages on a Visualforce page while executing Apex test methods. - createStub(parentType, stubProvider)
Creates a stubbed version of an Apex class that you can use for testing. This method is part of the Apex stub API. You can use it with the System.StubProvider interface to create a mocking framework. - enableChangeDataCapture()
Use this method in an Apex test so that change event notifications are generated for all supported Change Data Capture entities. Call this method at the beginning of your test before performing DML operations and calling Test.getEventBus().deliver();. - enqueueBatchJobs(numberOfJobs)
Adds the specified number of jobs with no-operation contents to the test-context queue. It first fills the test batch queue, up to the maximum 5 jobs, and then places jobs in the test flex queue. It throws a limit exception when the number of jobs in the test flex queue exceeds the allowed limit of 100 jobs. - getEventBus()
Returns an instance of the test event bus broker, which lets you operate on platform event or change event messages in an Apex test. For example, you can call Test.getEventBus().deliver() to deliver event messages. - getFlexQueueOrder()
Returns an ordered list of job IDs for jobs in the test-context flex queue. The job at index 0 is the next job slated to run. This method returns only test-context results, even if it’s annotated with @IsTest(SeeAllData=true). - getStandardPricebookId()
Returns the ID of the standard price book in the organization. - invokeContinuationMethod(controller, request)
Invokes the callback method for the specified controller and continuation in a test method. - isRunningTest()
Returns true if the currently executing code was called by code contained in a test method, false otherwise. Use this method if you need to run different code depending on whether it was being called from a test. - loadData(sObjectToken, resourceName)
Inserts test records from the specified static resource .csv file and for the specified sObject type, and returns a list of the inserted sObjects. - newSendEmailQuickActionDefaults(contextId, replyToId)
Creates a new QuickAction.SendEmailQuickActionDefaults instance for testing a class implementing the QuickAction.QuickActionDefaultsHandler interface. - setContinuationResponse(requestLabel, mockResponse)
Sets a mock response for a continuation HTTP request in a test method. - setCreatedDate(recordId, createdDatetime)
Sets CreatedDate for a test-context sObject. - setCurrentPage(page)
A Visualforce test method that sets the current PageReference for the controller. - setCurrentPageReference(page)
A Visualforce test method that sets the current PageReference for the controller. - setFixedSearchResults(fixedSearchResults)
Defines a list of fixed search results to be returned by all subsequent SOSL statements in a test method. - setMock(interfaceType, instance)
Sets the response mock mode and instructs the Apex runtime to send a mock response whenever a callout is made through the HTTP classes or the auto-generated code from WSDLs. - setReadOnlyApplicationMode(applicationMode)
Sets the application mode for an organization to read-only in an Apex test to simulate read-only mode during Salesforce upgrades and downtimes. The application mode is reset to the default mode at the end of each Apex test run. - startTest()
Marks the point in your test code when your test actually begins. Use this method when you are testing governor limits. - stopTest()
Marks the point in your test code when your test ends. Use this method in conjunction with the startTest method. - testInstall(installImplementation, version, isPush)
Tests the implementation of the InstallHandler interface, which is used for specifying a post-install script in packages. Tests run as the test initiator in the development environment. - testSandboxPostCopyScript(script, organizationId, sandboxId, sandboxName)
Tests the implementation of the ***, which is used for specifying a script to run at the completion of a Sandbox copy. Tests run as the test initiator in the development environment. - testUninstall(uninstallImplementation)
Tests the implementation of the UninstallHandler interface, which is used for specifying an uninstall script in packages. Tests run as the test initiator in the development environment.
For more know about the Test Methods in Test Class, Please Refer to this Article By clicking on this link: Apex Methods System Test
How to Create Test Data for the Test Class:
- Create the test data for the test class in the TestDataFactory Class.
@isTest
public class TestDataFactory {
public static List<Account> createAccountsWithOpps(Integer numAccts, Integer numOppsPerAcct) {
List<Account> accts = new List<Account>();
for(Integer i=0;i<numAccts;i++) {
Account a = new Account(Name='TestAccount' + i);
accts.add(a);
}
insert accts;
List<Opportunity> opps = new List<Opportunity>();
for (Integer j=0;j<numAccts;j++) {
Account acct = accts[j];
// For each account just inserted, add opportunities
for (Integer k=0;k<numOppsPerAcct;k++) {
opps.add(new Opportunity(Name=acct.Name + ' Opportunity ' + k,
StageName='Prospecting',
CloseDate=System.today().addMonths(1),
AccountId=acct.Id));
}
}
// Insert all opportunities for all accounts.
insert opps;
return accts;
}
}
- Call Utility Methods for Test Data Creation from the TestDataFactory
@isTest
private class TestAccountDeletion {
@isTest static void TestDeleteAccountWithOneOpportunity() {
// Test data setup
// Create one account with one opportunity by calling a utility method
Account[] accts = TestDataFactory.createAccountsWithOpps(1,1);
// Perform test
Test.startTest();
Database.DeleteResult result = Database.delete(accts[0], false);
Test.stopTest();
// Verify that the deletion should have been stopped by the trigger,
// so check that we got back an error.
System.assert(!result.isSuccess());
System.assert(result.getErrors().size() > 0);
System.assertEquals('Cannot delete account with related opportunities.',
result.getErrors()[0].getMessage());
}
}