---
schema_version: "1"
id: cd3528acfe301d0b69b99c20f2fb9406b264f18594a40e3a9deef23ba47f821f
title: Testing Example
collection: legacydeveloper
version: current
locale: en-us
portal_url: https://docs.salesforce.com/legacydeveloper/current/en-us/apexcode/apex_testing_example.md
canonical_url: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_example.htm
source_site: developer.salesforce.com
content_type: documentation
content_hash: e8e9d95f0a803ebdb35de09d3f9bd4c96db847b0ec6a6e4b87fbab68d0687e00
---
# Testing Example

The following example includes cases for the following types of tests:

- [Positive case with single and multiple records](#positive_test_case)
- [Negative case with single and multiple records](#negative_test_case)
- [Testing with other users](#second_user)

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.

@IsTest
private with sharing class MileageTrackerTestSuite {

    @IsTest
    static void runPositiveTestCases() {
        
        Double totalMiles = 0;
        final Double maxtotalMiles = 500;
        final Double singletotalMiles = 300;
        final Double u2Miles = 100;
  
        
        //Set up user
        User u1 = \[SELECT Id FROM User WHERE Alias='auser' WITH USER\_MODE\];
        
        //Run As U1
        System.RunAs(u1){

            
        System.debug('Inserting 300  miles... (single record validation)');
        
        Mileage\_\_c testMiles1 = new Mileage\_\_c(Miles\_\_c = 300, Date\_\_c = System.today());
        insert as user testMiles1;
        
        //Validate single insert
        for(Mileage\_\_c m:\[SELECT miles\_\_c FROM Mileage\_\_c 
            WHERE CreatedDate = TODAY
            and CreatedById = :u1.id
            and miles\_\_c != null WITH USER\_MODE\]) {
                totalMiles += m.miles\_\_c;
            }
        
        Assert.areEqual(singletotalMiles, totalMiles);
    
    
        //Bulk validation   
        totalMiles = 0; 
        System.debug('Inserting 200 mileage records... (bulk validation)');
        
        List<Mileage\_\_c> testMiles2 = new List<Mileage\_\_c>();
        for(integer i=0; i<200; i++) {
            testMiles2.add( new Mileage\_\_c(Miles\_\_c = 1, Date\_\_c = System.today()) );
        }
        insert as user testMiles2;
       
        for(Mileage\_\_c m:\[SELECT miles\_\_c FROM Mileage\_\_c
            WHERE CreatedDate = TODAY
            and CreatedById = :u1.Id
            and miles\_\_c != null WITH USER\_MODE\]) {
                totalMiles += m.miles\_\_c;
            }
        
        Assert.areEqual(maxtotalMiles, totalMiles);

        }//end RunAs(u1)

       //Validate additional user:
       totalMiles = 0;
       //Setup RunAs
       User u2 = \[SELECT Id FROM User WHERE Alias='tuser' WITH USER\_MODE\];
       System.RunAs(u2){
        
        Mileage\_\_c testMiles3 = new Mileage\_\_c(Miles\_\_c = 100, Date\_\_c = System.today());
        insert as user testMiles3;
        
                for(Mileage\_\_c m:\[SELECT miles\_\_c FROM Mileage\_\_c
            WHERE CreatedDate = TODAY
            and CreatedById = :u2.Id
            and miles\_\_c != null WITH USER\_MODE\]) {
                totalMiles += m.miles\_\_c;
            }
        //Validate 
        Assert.areEqual(u2Miles, totalMiles);
        
       } //System.RunAs(u2)

      
    } // runPositiveTestCases()
   
    @IsTest
    static void runNegativeTestCases() {

        User u3 = \[SELECT Id FROM User WHERE Alias='tuser' WITH USER\_MODE\];
        System.RunAs(u3) {

           System.debug('Inserting a record with 501 miles... (negative test case)'); 

           Mileage\_\_c testMiles3 = new Mileage\_\_c( Miles\_\_c = 501, Date\_\_c = System.today() );

           try {
               insert as user testMiles3;
               Assert.fail('DmlException expected');
           } catch (DmlException e) {
               //Assert Status Code
               Assert.areEqual('FIELD\_CUSTOM\_VALIDATION\_EXCEPTION', e.getDmlStatusCode(0));
            
               //Assert field
               Assert.areEqual(Mileage\_\_c.Miles\_\_c, e.getDmlFields(0)\[0\]);
                        
               //Assert Error Message
               Assert.isTrue(e.getMessage().contains(
                'Mileage request exceeds daily limit(500): \[Miles\_\_c\]'),
                'DMLException did not contain expected validation message:' + e.getMessage() );
            
             } //catch
           } //RunAs(u3) 
    } // runNegativeTestCases() 
  
    
} // 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:
    
    System.debug('Inserting 300 more miles...single record validation');
2. Create a Mileage\_\_c object and insert it into the database.
    
    Mileage\_\_c testMiles1 = new Mileage\_\_c(Miles\_\_c = 300, Date\_\_c = System.today() );
    insert as user testMiles1;
3. Validate the code by returning the inserted records:
    
    for(Mileage\_\_c m:\[SELECT miles\_\_c FROM Mileage\_\_c 
       WHERE CreatedDate = TODAY 
       and CreatedById = :createdbyId 
       and miles\_\_c != null WITH USER\_MODE\]) {
           totalMiles += m.miles\_\_c;
        }
4. Use the Assert.areEqual method to verify that the expected result is returned:
    
    Assert.areEqual(singletotalMiles, totalMiles);
5. Before moving to the next test, set the number of total miles back to 0:
    
    totalMiles = 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:
    
    System.debug('Inserting 200 Mileage records...bulk validation');
7. Then insert 200 Mileage\_\_c records:
    
    List<Mileage\_\_c> testMiles2 = new List<Mileage\_\_c>();
    for(Integer i=0; i<200; i++){
    testMiles2.add( new Mileage\_\_c(Miles\_\_c = 1, Date\_\_c = System.today()) );
       }
    insert as user testMiles2;
8. Use Assert.areEqual to verify that the expected result is returned:
    
    for(Mileage\_\_c m:\[SELECT miles\_\_c FROM Mileage\_\_c 
       WHERE CreatedDate = TODAY 
       and CreatedById = :CreatedbyId 
       and miles\_\_c != null WITH USER\_MODE\]) {
           totalMiles += m.miles\_\_c;
        }
           Assert.areEqual(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:
    
    @IsTest
    static void runNegativeTestCases(){
2. Add text to the debug log, indicating the next step of the code:
    
    System.debug('Inserting 501 miles... negative test case');
3. Create a Mileage\_\_c record with 501 miles.
    
    Mileage\_\_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. Use the Assert.fail method to clearly assert that you expect the validation exception.
    
    try {
         insert as user testMiles3;
         Assert.fail('DmlException expected');
         } catch (DmlException e) {
5. Now use the Assert.areEqual and Assert.isTrue methods to do the testing. Add the following code to the catch block you previously created:
    
    //Assert Status Code
    Assert.areEqual('FIELD\_CUSTOM\_VALIDATION\_EXCEPTION', e.getDmlStatusCode(0));
                
    //Assert field
    Assert.areEqual(Mileage\_\_c.Miles\_\_c, e.getDmlFields(0)\[0\]);
                            
    //Assert Error Message
    Assert.isTrue(e.getMessage().contains(
      'Mileage request exceeds daily limit(500): \[Miles\_\_c\]'),
      'DMLException did not contain expected validation message:' + e.getMessage() );

## 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:
    
    totalMiles = 0;
2. Set up the next user.
    
           User u2 = \[SELECT Id FROM User WHERE Alias='tuser' WITH USER\_MODE\];
           System.RunAs(u2){
3. Add text to the debug log, indicating the next step of the code:
    
            System.debug('Setting up testing - deleting any mileage records for ' +
                UserInfo.getUserName() +
                ' from today');
4. Then insert one Mileage\_\_c record:
    
    Mileage\_\_c testMiles3 = new Mileage\_\_c(Miles\_\_c = 100, Date\_\_c = System.today());
    insert as user testMiles3;
5. Validate the code by returning the inserted records:
    
    for(Mileage\_\_c m:\[SELECT miles\_\_c FROM Mileage\_\_c 
       WHERE CreatedDate = TODAY 
       and CreatedById = :u2.Id 
       and miles\_\_c != null WITH USER\_MODE\]) {
           totalMiles += m.miles\_\_c;
        }
6. Use the Assert.areEqual method to verify that the expected result is returned:
    
    Assert.areEqual(u2Miles, totalMiles);