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.

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