Newer Version Available
Testing Example
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.
Positive Test Case
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.areEqual method 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.areEqual to verify that the expected result
is
returned:
Negative Test Case
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 insert statement within a try/catch block. This allows you to catch the validation exception and
assert the generated error message. Use the Assert.fail method to clearly assert that you expect the
validation exception.
- Now use the Assert.areEqual and Assert.isTrue methods to do the testing.
Add the following code to the catch
block you previously
created:
Testing as a Second User
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.areEqual method to verify that the
expected result is
returned: