Newer Version Available

This content describes an older version of this product. View Latest

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. Here is the entire test class. The following sections step through specific portions of the code.

1@isTest
2private class MileageTrackerTestSuite {
3
4    static testMethod void runPositiveTestCases() {
5        
6        Double totalMiles = 0;
7        final Double maxtotalMiles = 500;
8        final Double singletotalMiles = 300;
9        final Double u2Miles = 100;
10  
11        
12        //Set up user
13        User u1 = [SELECT Id FROM User WHERE Alias='auser'];
14        
15        //Run As U1
16        System.RunAs(u1){
17
18            
19        System.debug('Inserting 300  miles... (single record validation)');
20        
21        Mileage__c testMiles1 = new Mileage__c(Miles__c = 300, Date__c = System.today());
22        insert testMiles1;
23        
24        //Validate single insert
25        for(Mileage__c m:[SELECT miles__c FROM Mileage__c 
26            WHERE CreatedDate = TODAY
27            and CreatedById = :u1.id
28            and miles__c != null]) {
29                totalMiles += m.miles__c;
30            }
31        
32        System.assertEquals(singletotalMiles, totalMiles);
33    
34    
35        //Bulk validation   
36        totalMiles = 0; 
37        System.debug('Inserting 200 mileage records... (bulk validation)');
38        
39        List<Mileage__c> testMiles2 = new List<Mileage__c>();
40        for(integer i=0; i<200; i++) {
41            testMiles2.add( new Mileage__c(Miles__c = 1, Date__c = System.today()) );
42        }
43        insert testMiles2;
44       
45        for(Mileage__c m:[SELECT miles__c FROM Mileage__c
46            WHERE CreatedDate = TODAY
47            and CreatedById = :u1.Id
48            and miles__c != null]) {
49                totalMiles += m.miles__c;
50            }
51        
52        System.assertEquals(maxtotalMiles, totalMiles);
53
54        }//end RunAs(u1)
55
56
57       //Validate additional user:
58       totalMiles = 0;
59       //Setup RunAs
60       User u2 = [SELECT Id FROM User WHERE Alias='tuser'];
61       System.RunAs(u2){
62        
63        Mileage__c testMiles3 = new Mileage__c(Miles__c = 100, Date__c = System.today());
64        insert testMiles3;
65        
66                for(Mileage__c m:[SELECT miles__c FROM Mileage__c
67            WHERE CreatedDate = TODAY
68            and CreatedById = :u2.Id
69            and miles__c != null]) {
70                totalMiles += m.miles__c;
71            }
72        //Validate 
73        System.assertEquals(u2Miles, totalMiles);
74        
75       } //System.RunAs(u2)
76
77      
78    } // runPositiveTestCases()
79   
80    static testMethod void runNegativeTestCases() {
81
82       User u3 = [SELECT Id FROM User WHERE Alias='tuser'];
83       System.RunAs(u3){
84        
85       System.debug('Inserting a record with 501 miles... (negative test case)');
86        
87       Mileage__c testMiles3 = new Mileage__c( Miles__c = 501, Date__c = System.today() );
88        
89        try {
90            insert testMiles3;
91        } catch (DmlException e) {
92            //Assert Error Message
93            System.assert( e.getMessage().contains('Insert failed. First exception on ' +
94                'row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, ' +
95                'Mileage request exceeds daily limit(500): [Miles__c]'), 
96                e.getMessage() );
97                  
98            //Assert field
99            System.assertEquals(Mileage__c.Miles__c, e.getDmlFields(0)[0]);
100            
101            //Assert Status Code
102            System.assertEquals('FIELD_CUSTOM_VALIDATION_EXCEPTION' , 
103                                 e.getDmlStatusCode(0) );
104        } //catch
105       } //RunAs(u3) 
106    } // runNegativeTestCases() 
107  
108    
109} // class MileageTrackerTestSuite

Positive Test Case

The following steps through the above code, in particular, the positive test case for single and multiple records.

  1. Add text to the debug log, indicating the next step of the code:
    1System.debug('Inserting 300 more miles...single record validation');
  2. Create a Mileage__c object and insert it into the database.
    1Mileage__c testMiles1 = new Mileage__c(Miles__c = 300, Date__c = System.today() );
    2insert testMiles1;
  3. Validate the code by returning the inserted records:
    1for(Mileage__c m:[SELECT miles__c FROM Mileage__c 
    2   WHERE CreatedDate = TODAY 
    3   and CreatedById = :createdbyId 
    4   and miles__c != null]) {
    5       totalMiles += m.miles__c;
    6    }
  4. Use the system.assertEquals method to verify that the expected result is returned:
    1System.assertEquals(singletotalMiles, totalMiles);
  5. Before moving to the next test, set the number of total miles back to 0:
    1totalMiles = 0;
  6. 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:
    1System.debug('Inserting 200 Mileage records...bulk validation');
  7. Then insert 200 Mileage__c records:
    1List<Mileage__c> testMiles2 = new List<Mileage__c>();
    2for(Integer i=0; i<200; i++){
    3testMiles2.add( new Mileage__c(Miles__c = 1, Date__c = System.today()) );
    4   }
    5insert testMiles2;
  8. Use System.assertEquals to verify that the expected result is returned:
    1for(Mileage__c m:[SELECT miles__c FROM Mileage__c 
    2   WHERE CreatedDate = TODAY 
    3   and CreatedById = :CreatedbyId 
    4   and miles__c != null]) {
    5       totalMiles += m.miles__c;
    6    }
    7       System.assertEquals(maxtotalMiles, totalMiles);

Negative Test Case

The following steps through the above code, in particular, the negative test case.

  1. Create a static test method called runNegativeTestCases:
    1static testMethod void runNegativeTestCases(){
  2. Add text to the debug log, indicating the next step of the code:
    1System.debug('Inserting 501 miles... negative test case');
  3. Create a Mileage__c record with 501 miles.
    1Mileage__c testMiles3 = new Mileage__c(Miles__c = 501, Date__c = System.today());
  4. Place the insert statement within a try/catch block. This allows you to catch the validation exception and assert the generated error message.
    1try {
    2     insert testMiles3;
    3     } catch (DmlException e) {
  5. Now use the System.assert and System.assertEquals to do the testing. Add the following code to the catch block you previously created:
    1//Assert Error Message
    2   System.assert(e.getMessage().contains('Insert failed. First exception '+
    3      'on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, '+
    4      'Mileage request exceeds daily limit(500): [Miles__c]'), 
    5         e.getMessage()); 
    6
    7//Assert Field
    8   System.assertEquals(Mileage__c.Miles__c, e.getDmlFields(0)[0]);
    9
    10//Assert Status Code
    11   System.assertEquals('FIELD_CUSTOM_VALIDATION_EXCEPTION'  , 
    12                        e.getDmlStatusCode(0));
    13          }
    14   }
    15}

Testing as a Second User

The following steps through the above code, in particular, running as a second user.

  1. Before moving to the next test, set the number of total miles back to 0:
    1totalMiles = 0;
  2. Set up the next user.
    1User u2 = [SELECT Id FROM User WHERE Alias='tuser'];
    2       System.RunAs(u2){
  3. Add text to the debug log, indicating the next step of the code:
    1System.debug('Setting up testing - deleting any mileage records for ' +
    2            UserInfo.getUserName() +
    3            ' from today');
  4. Then insert one Mileage__c record:
    1Mileage__c testMiles3 = new Mileage__c(Miles__c = 100, Date__c = System.today());
    2insert testMiles3;
  5. Validate the code by returning the inserted records:
    1for(Mileage__c m:[SELECT miles__c FROM Mileage__c 
    2   WHERE CreatedDate = TODAY 
    3   and CreatedById = :u2.Id 
    4   and miles__c != null]) {
    5       totalMiles += m.miles__c;
    6    }
  6. Use the system.assertEquals method to verify that the expected result is returned:
    1System.assertEquals(u2Miles, totalMiles);