How can the “test.starttest” and “test.stoptest” method help in my unit test?

240    Asked by david_2585 in Salesforce , Asked on Apr 22, 2024

 I am currently engaged in a particular task that is related to writing a unit test for a complex apex class in Salesforce. Explain to me how the “test.starttest” and “test.stoptest” methods help in my unit test. 

Answered by Crowny Hasegawa

In the context of Salesforce, here is the explanation given of how you can use both methods:-

Both these methods are the methods which are provided by the Salesforce apex testing framework for helping the developer control the implementation of the context of their unit tests. The start test marks the beginning of a block while the stoptest marks the end of that block.

The test.starttest and test.stoptest can help reset the governor limits which would help allow the developers to test their code functionally without being constrained by limits.

These methods can ensure that any asynchronous operations should be started within the test block.

If you run the code within the test blocks, then you as a developer can isolate your test cases from the other test method or existing data which would ensure a clean and predictable testing environment.

Here is the example given how you can use both the above method in Salesforce unit testing:-

@isTest
Public class AccountManagerTest {
    @isTest
    Static void testCreateAccount() {
        // Test data setup
        Account acc = new Account(Name = ‘Test Account’, Industry = ‘Technology’);
        // Start the test execution block
        Test.startTest();
        // Insert the Account record within the test block
        Insert acc;
        // Stop the test execution block
        Test.stopTest();
        // Retrieve the inserted Account record
        Account insertedAccount = [SELECT Id, Name, Industry FROM Account WHERE Name = ‘Test Account’ LIMIT 1];
        // Assert that the Account was inserted successfully
        System.assertNotEquals(null, insertedAccount);
        System.assertEquals(‘Test Account’, insertedAccount.Name);
        System.assertEquals(‘Technology’, insertedAccount.Industry);
    }
    @isTest
    Static void testUpdateAccount() {
        // Test data setup
        Account acc = new Account(Name = ‘Test Account’, Industry = ‘Technology’);
        Insert acc;
        // Start the test execution block
        Test.startTest();
        // Update the Account record within the test block
        Acc.Industry = ‘Healthcare’;
        Update acc;
        // Stop the test execution block
        Test.stopTest();
        // Retrieve the updated Account record        Account updatedAccount = [SELECT Id, Name, Industry FROM Account WHERE Id = :acc.Id LIMIT 1];
        // Assert that the Account was updated successfully
        System.assertNotEquals(null, updatedAccount);
        System.assertEquals(‘Healthcare’, updatedAccount.Industry);
    }

    @isTest

    Static void testDeleteAccount() {
        // Test data setup
        Account acc = new Account(Name = ‘Test Account’, Industry = ‘Technology’);
        Insert acc;
        // Start the test execution block
        Test.startTest();
        // Delete the Account record within the test block
        Delete acc;
        // Stop the test execution block
        Test.stopTest();
        // Retrieve the deleted Account record
        Account deletedAccount = [SELECT Id, Name, Industry FROM Account WHERE Id = :acc.Id LIMIT 1];
        // Assert that the Account was deleted successfully
        System.assertEquals(null, deletedAccount);
    }
}
Here is the same example given in python programming language:-
From unittest.mock import MagicMock
Import unittest
Class AccountManager:
    Def __init__(self, salesforce_connection):
        Self.salesforce_connection = salesforce_connection
    Def create_account(self, name, industry):
        Account = {‘Name’: name, ‘Industry’: industry}
        Return self.salesforce_connection.insert_record(‘Account’, account)
    Def update_account(self, account_id, industry):
        Account = {‘Id’: account_id, ‘Industry’: industry}
        Return self.salesforce_connection.update_record(‘Account’, account)
    Def delete_account(self, account_id):
        Return self.salesforce_connection.delete_record(‘Account’, account_id)
Class SalesforceConnection:
    Def insert_record(self, object_type, record):
        # Simulated insert operation
        Print(f”Inserting {object_type} record: {record}”)
        Return ‘001R00000123456’
    Def update_record(self, object_type, record):
        # Simulated update operation
        Print(f”Updating {object_type} record: {record}”)
        Return True
    Def delete_record(self, object_type, record_id):
        # Simulated delete operation
        Print(f”Deleting {object_type} record with ID: {record_id}”)
        Return True
Class TestAccountManager(unittest.TestCase):
    Def test_create_account(self):
        # Mock Salesforce connection
        Salesforce_connection = SalesforceConnection()
        Salesforce_connection.insert_record = MagicMock(return_value=’001R00000123456’)
        # Create AccountManager instance
        Account_manager = AccountManager(salesforce_connection)
        # Start the test execution block
        With unittest.mock.patch(‘builtins.print’) as mock_print:
            Account_id = account_manager.create_account(‘Test Account’, ‘Technology’)
            # Assert the mock insert_record method was called with correct arguments
            Salesforce_connection.insert_record.assert_called_once_with(‘Account’, {‘Name’: ‘Test Account’, ‘Industry’: ‘Technology’})
            Mock_print.assert_any_call(“Inserting Account record: {‘Name’: ‘Test Account’, ‘Industry’: ‘Technology’}”)
        # Stop the test execution block
        # No need for stopTest in Python unittest, as the context manager with unittest.mock.patch handles it implicitly
        # Assert the account_id returned by create_account
        Self.assertEqual(account_id, ‘001R00000123456’)
    Def test_update_account(self):
        # Mock Salesforce connection
        Salesforce_connection = SalesforceConnection()
        Salesforce_connection.update_record = MagicMock(return_value=True)
        # Create AccountManager instance
        Account_manager = AccountManager(salesforce_connection)
        # Start the test execution block
        With unittest.mock.patch(‘builtins.print’) as mock_print:
            Success = account_manager.update_account(‘001R00000123456’, ‘Healthcare’)
            # Assert the mock update_record method was called with correct arguments
            Salesforce_connection.update_record.assert_called_once_with(‘Account’, {‘Id’: ‘001R00000123456’, ‘Industry’: ‘Healthcare’})
            Mock_print.assert_any_call(“Updating Account record: {‘Id’: ‘001R00000123456’, ‘Industry’: ‘Healthcare’}”)
        # Stop the test execution block
        # No need for stopTest in Python unittest, as the context manager with unittest.mock.patch handles it implicitly
        # Assert the success flag returned by update_account
        Self.assertTrue(success)
    Def test_delete_account(self):
        # Mock Salesforce connection
        Salesforce_connection = SalesforceConnection()
        Salesforce_connection.delete_record = MagicMock(return_value=True)
        # Create AccountManager instance
        Account_manager = AccountManager(salesforce_connection)
        # Start the test execution block
        With unittest.mock.patch(‘builtins.print’) as mock_print:
            Success = account_manager.delete_account(‘001R00000123456’)
            # Assert the mock delete_record method was called with correct arguments
            Salesforce_connection.delete_record.assert_called_once_with(‘Account’, ‘001R00000123456’)
            Mock_print.assert_any_call(“Deleting Account record with ID: 001R00000123456”)
        # Stop the test execution block
        # No need for stopTest in Python unittest, as the context manager with unittest.mock.patch handles it implicitly
        # Assert the success flag returned by delete_account
        Self.assertTrue(success)
If __name__ == ‘__main__’:
    Unittest.main()


Your Answer

Interviews

Parent Categories