Testing Strategies for Developer
Jun12

Testing Strategies for Developer

Salesforce provides a framework for testing apex code. Testing is the key to successful software development. Before deploying apex code, try to cover as many lines of code as you can. At least 75% of your Apex code must be covered by unit tests else your code will not be deployed to production. Why Test? You should not write test classes by keeping in my mind just to cover 75% of your code but should always try to cover your entire code before deploying to production. Test provides assurance of functionality Test reduce cost of change Test encourage modular and reusable code Test help document expected behavior Test + Code = less likely produce the bug What to Test? Things that should happen to happen (Positive) : Positive testing is a way to test expected behaviour of code that you wrote is suppose to do. Things that should not happen to happen (Negative) : This is the hardest and important thing to test that verify if the error messages are correctly produced along with the positive working of test cases, within the limits cases. User Access : This is basically the manual testing, which we perform by seeing the aspect of end-user test is done when we think of user interaction. This type of test is done by hand via insert, update, delete and undelete the records. Exceptions : Exception testing tests expected behaviour of code when an user with restricted access to sObjects are used in code. Bulk Testing : This test comes in when a class, trigger or any apex code insert and update data in bulk. We need to test the class by creating more than one record in multiple scenarios. Test Structure Principles for Best Practices Principle #1  Use of Asserts : Assert is the method of System Class. It is an important method for test class which is used to check the expected result of test scenario. “A test without assert method isn’t a test, it’s code execution.” There are three in-built assert methods which are as follows: assert(condition, message) assertEquals(expected, actual, message) assertNotEquals(expected, actual, message) Every test method should include at least one assertion. Principle #2   Use startTest() and stopTest() startTest() methods are used to reset governor limits. The code between Test.startTest and Test.stopTest executes in fresh set of governor limits that means your setup code will not interfere and give you false positives (or negatives) surrounding governor limits. stopTest() method focuses on asynchronous code to complete. In general, one should follow these steps while writing test class: Create your test data Start the test Use that test data within your tested...

Read More