Testing Example
The following example includes cases for the following types of tests:
- Positive case with single and multiple records
- Negative case with single and multiple records
- Testing with other users
The test is used with a simple mileage tracking application. The existing code for the application verifies that not more than 500 miles are entered in a single day. The primary object is a custom object named Mileage__c. The test creates one record with 300 miles and verifies there are only 300 miles recorded. Then a loop creates 200 records with one mile each. Finally, it verifies there are 500 miles recorded in total (the original 300 plus the new ones). Here’s the entire test class. The following sections step through specific portions of the code.
The following steps through the above code, in particular, the positive test case for single and multiple records.
-
Add text to the debug log, indicating the next step of the code:
-
Create a Mileage__c object and insert it into the database.
-
Validate the code by returning the inserted records:
-
Use the
Assert.areEqualmethod to verify that the expected result is returned: -
Before moving to the next test, set the number of total miles back to 0:
-
Validate the code by creating a bulk insert of 200 records.
First, add text to the debug log, indicating the next step of the code:
-
Then insert 200 Mileage__c records:
-
Use
Assert.areEqualto verify that the expected result is returned:
The following steps through the above code, in particular, the negative test case.
-
Create a static test method called
runNegativeTestCases: -
Add text to the debug log, indicating the next step of the code:
-
Create a Mileage__c record with 501 miles.
-
Place the
insertstatement within atry/catchblock. This allows you to catch the validation exception and assert the generated error message. Use theAssert.failmethod to clearly assert that you expect the validation exception. -
Now use the
Assert.areEqualandAssert.isTruemethods to do the testing. Add the following code to thecatchblock you previously created:
The following steps through the above code, in particular, running as a second user.
-
Before moving to the next test, set the number of total miles back to 0:
-
Set up the next user.
-
Add text to the debug log, indicating the next step of the code:
-
Then insert one Mileage__c record:
-
Validate the code by returning the inserted records:
-
Use the
Assert.areEqualmethod to verify that the expected result is returned: