Test class interview questions in Salesforce 2024

1. What is a test class in Salesforce, and why is it important?

A test class is a class written in Apex to test the functionality of another Apex class. In Salesforce, it’s crucial to have test classes to ensure that your code works as expected and to meet the platform’s code coverage requirements.

For the development of robust, error-free code, It is necessary to have some mechanism which ensures whether a particular piece of code is working properly or not and for that Apex supports the creation and execution of unit tests. Unit tests are class methods that verify whether a particular piece of code is working properly. Unit test methods take no arguments, commit no data to the database.

2. How can you invoke a test class in Salesforce?

Test classes in Salesforce are invoked automatically when you deploy code or manually by running the tests using the Salesforce Developer Console, Salesforce CLI, or through the Salesforce Setup menu.

3. Does Salesforce count calls to system.debug() against the code coverage?

No, Salesforce does not count it against the code coverage.

4. How many types of Assert Statements are there and what is their purpose?

Assert statements are used to compare expected value with the actual value.

There are three types of assert statements :

  1. assertEquals(expVal, actVal); returns true if expVal Matches actVal.
  2. assertNotEqual(expVal, actVal); returns true if expVal does not match actVal.
  3. assertEquals(expVal > actVal); returns true if the condition is satisfied.

5. What is the purpose of the @isTest and @TestSetup annotation in Apex?

The @isTest annotation is used to define a class or method as a test class or test method. It allows the Apex compiler to recognize the class or method as containing test code that should not be counted against the organization’s code size limit.

The @TestSetup annotation is used to define methods that are called once to create test records shared by all test methods in the test class. It helps reduce code duplication and ensures a consistent test environment.

6. How do you ensure proper code coverage in a test class?

Code coverage is the percentage of your code that is tested by your test classes. To ensure proper code coverage, write test methods that cover the positive and negative scenarios of your Apex code. Aim for at least 75% code coverage for your classes and 1% for triggers. Use assert statements to verify expected results and isolate test data to maintain a controlled environment. Additionally, consider testing asynchronous code paths, leverage Test.isRunningTest for conditional execution during testing, and regularly review and update your test coverage as your code evolves. These practices collectively contribute to robust testing, ensuring the reliability and quality of your Salesforce Apex code.

7. What is the difference between Test.startTest() and Test.stopTest() in a test class?

Test.startTest() and Test.stopTest() help in setting a boundary around the code that is being tested. This ensures that the governor limits, or restrictions on resources, are accurately measured only for the specific portion of code being tested in a Salesforce test class. Basically they help to create a fresh set of governing limit.

The governor limits are reset after Test.startTest(), and the cumulative resource usage is calculated up to Test.stopTest(). Each test method can call the start test and stop test only once.

8. Explain the concept of system asserts in Salesforce test classes.

System asserts are used to verify that the behavior of a piece of code is as expected. Common system asserts include System.assertEquals, System.assertNotEquals, and System.assert, which are used to check expected and actual values.

9. What is the purpose of the SeeAllData=true attribute in a test class?

The SeeAllData=true attribute allows test methods to access and manipulate data in the organization, including existing records. It is generally discouraged as it can lead to test failures in different environments due to variations in data.

10. How do you create test data for your test classes in Salesforce?

Test data is created using Test.loadData for static records or by inserting records within the test method. It’s good practice to create test data within the test method to ensure that the data is specific to the test case being executed.

11. How can you test governor limit exceptions in a test class?

You can use the Test.startTest() and Test.stopTest() methods to measure the cumulative resource usage within a specific portion of code and assert against expected governor limit exceptions.

12. Can you use the actual database records in a test class? Why or why not?

To ensure the reliability and portability of your test classes, it’s recommended to create and use test data within the test class itself, rather than relying on actual database records. If you do need to access real data, make sure to use SeeAllData=true cautiously and understand the potential implications on test behavior and portability.

13. What is the use of seeAllData=false ?

If we are defining a test class with @isTest(SeeAllData=false) then we cannot access data in test class from the database under all method present in the test class. Under this case annotating a method with @isTest(SeeAllData=true) would not be ignored and you can access database data inside this method.

14. How do you test triggers in Salesforce?

To test triggers, create records within the test method that will cause the trigger to execute. Use assertions to verify the expected changes caused by the trigger.

For example, if your trigger is designed to update a field when a record meets certain criteria, use assertions to confirm that the field has been updated as expected. This approach helps ensure that your trigger logic is functioning correctly and produces the desired results during testing.

15. What is the purpose of the @TestVisible annotation in Apex?

The @TestVisible annotation in Apex is used to make methods and variables visible to test classes, even if they are private. In Apex, methods and variables with the private access modifier are not directly accessible in test classes. However, by adding the @TestVisible annotation to a method or variable, you grant visibility to those elements specifically for testing purposes.

This annotation is particularly useful when you want to test certain aspects of your code that are not meant to be exposed publicly but need to be examined or manipulated during testing. It allows you to maintain encapsulation in your production code while providing the necessary visibility for testing scenarios.

16. How can you test a class that performs email messaging in Salesforce?

Use the Messaging.SendEmailResult class to capture the results of email sending operations. In the test method, assert against the expected email sending behavior.

To test a Salesforce class for sending emails, put the email part in its own method. Send emails using Messaging.sendEmail, and pretend to send them using Test.isRunningTest(). Check if emails are ready to be sent with assertions or Limits.getEmailInvocations(). Look at email content and who it’s sent to. Try different situations like using different email templates and dealing with errors. Make sure your tests don’t depend on real email data by adding @isTest(SeeAllData=false) to your test methods.

17. What is the purpose of the Test.getStandardPricebookId() method?

The Test.getStandardPricebookId() method in Salesforce is used in test classes to retrieve the ID of the standard price book. This method is particularly handy when testing scenarios involving price books, allowing developers to reference the standard price book ID within the isolated context of a test method.

18. What is the use of test.isrunningtest()?

Sometimes it may happen that in test class you are not able to satisfy certain condition in apex class so under this case, we can bypass this condition by writing test.isrunningtest() in apex class.

19. What is System.runAs() in test class?

Test class runs in system mode, System.runAs() allow us to run the test in context of current user where user ‘s record sharing is taken into account. User permission or field level permission are not taken into account.

20. How many @testSetup method are supported inside a test class?

One test setup method per test class.

21. 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.

22. Let say 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.

23. How to test callouts using HttpCalloutMock Interfaces?

Certainly! When you need to test code that makes HTTP callouts in Salesforce, you can’t directly use test methods because they can’t perform real callouts. Instead, you use something called “mock callouts.”

  • To test callouts, Salesforce provides a solution called “mock callouts.”
  • Create a class that implements the HttpCalloutMock interface. This class can be either global or public.
  • You can annotate this class with @isTest to ensure it’s only used in a test context. This annotation helps exclude it from your organization’s code size limit of 6 MB.

24. What are test class best practices?

Here’s a concise list of Salesforce test class best practices:

  • Code Coverage: Maintain at least 75% code coverage for classes and 1% for triggers.
  • Isolate Test Data: Create test data within the test class for consistency and independence.
  • Use @isTest Annotation: Designate test classes with @isTest to avoid code size limits.
  • Test Bulk Data: Ensure test methods handle scenarios with bulk data processing.
  • Test.startTest() and Test.stopTest(): Enclose asynchronous code between these methods for accurate governor limit calculations.
  • Implement Assertions: Use assertions to validate expected code behavior.
  • Test Positive and Negative Scenarios: Cover both positive and negative scenarios in test methods.
  • Avoid SeeAllData=true: Refrain from using this attribute for reliable and environment-independent tests.
  • Test Bulk Triggers: Ensure triggers are tested for bulk data scenarios.
  • Use @TestSetup Annotation: Employ @TestSetup for shared test data among methods.
  • Handle Exceptions: Implement try-catch blocks to handle exceptions gracefully.

Useful Links








Leave a Reply

Your email address will not be published. Required fields are marked *