Test methods using DML and SOQL

To test the Apex Trigger methods of the Domain class, the traditional use of DML and SOQL can be applied alongside the use of the Apex runtime DMLException methods to assert not only the error message but also other details. The following Apex test method illustrates how to do this:

@IsTest 
private static void testAddContestantNoneScheduled() { 
  // Test data 
  Season__c season =  
    new Season__c(Name = '2014', Year__c = '2014'); 
  insert season; 
  Driver__c driver =  
    new Driver__c(
Name = 'Lewis Hamilton', DriverId__c = '42'); insert driver; Race__c race = new Race__c(Name = 'Spa',
Status__c = 'In Progress', Season__c = season.Id); insert race; Test.startTest(); try { // Insert Contestant to In Progress race Contestant__c contestant = new Contestant__c(
Driver__c = driver.Id,
Race__c = race.Id); insert contestant; System.assert(false, 'Expected exception'); } catch (DMLException e) { System.assertEquals(1, e.getNumDml()); System.assertEquals( 'Contestants can only be added to Scheduled Races.', e.getDmlMessage(0)); System.assertEquals( StatusCode.FIELD_CUSTOM_VALIDATION_EXCEPTION, e.getDmlType(0)); } Test.stopTest(); }

The preceding error is a record-level error; the DMLException class also allows you to assert field-level information for field-level errors. The following code shows such a test assertion; note that the data setup code is not shown:

Test.startTest(); 
Try { 
  contestant.Driver__c = anotherDriver.Id; 
  update contestant; 
  System.assert(false, 'Expected exception'); 
} 
catch (DmlException e) { 
  System.assertEquals(1, e.getNumDml()); 
  System.assertEquals( 
    'You can only change drivers for scheduled races', 
    e.getDmlMessage(0)); 
  System.assertEquals(Contestant__c.Driver__c, 
    e.getDmlFields(0)[0]); 
  System.assertEquals( 
   StatusCode.FIELD_CUSTOM_VALIDATION_EXCEPTION,  
   e.getDmlType(0)); 
} 
Test.stopTest(); 

In this section, the Domain class logic was tested indirectly by observing the outcome of inserting and updating records into the database. This will only test methods associated with those operations. In the next section, we will see how to test custom Domain class methods.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.29.209