Saturday, April 21, 2012

Salesforce: System.Assert v/s System.AssertEquals

System.Assert v/s System.AssertEquals

If we talk out main differences in between to then we found out that:-

System.Assert accepts two parameters, one (mandatory) which is the condition to test for and the other a message (optional) to display should that condition be false.

System.AssertEquals and System.AssertNotEquals both accepts three parameters; the first two (mandatory) are the variables that will be tested for in/equality and the third (optional) is the message to display if the assert results in false.

Now testing best practices state that you should assert some condition but also output a “console” message that shows the values of each of the operands. This certainly helps you debug unit tests when asserts are failing,It is like wasting time to check out some variable values! So the time saving trick that isn’t obvious is that when omitting the optional third parameter for System.AssertEquals and System.AssertNotEquals the compiler automatically outputs the values of the operands to the console log. That’s right, instead of typing:

In Case of System.Assert

 System.assert(var1 == var2, "The value of var1 is: " +var1 + " and the value of... oh hell I  don't care I mean it's just a variable");

You could type:

System.assertEquals(var1, var2);

If the second assertion fails the console will output the values of var1 and var2 with the labels “expected” and “actual”. Knowing this now I can see no exceptional reason to use System.assert any longer.
Example for System.Assert

/**
 * This class contains unit tests for validating the behavior of Apex classes
 * and triggers.
 *
 * Unit tests are class methods that verify whether a particular piece
 * of code is working properly. Unit test methods take no arguments,
 * commit no data to the database, and are flagged with the testMethod
 * keyword in the method definition.
 *
 * All test methods in an organization are executed whenever Apex code is deployed
 * to a production organization to confirm correctness, ensure code
 * coverage, and prevent regressions. All Apex classes are
 * required to have at least 75% code coverage in order to be deployed
 * to a production organization. In addition, all triggers must have some code coverage.
 *
 * The @isTest class annotation indicates this class only contains test
 * methods. Classes defined with the @isTest annotation do not count against
 * the organization size limit for all Apex scripts.
 *
 * See the Apex Language Reference for more information about Testing and Code Coverage.
 */
@isTest
private class TestCheckInTrigger {
    static testMethod void myUnitTest() {
      
        // Insert Room
          Room__c room = new Room__c(Rent__c=2000.00, Type__c='AC',Room_No__c='RN_121'; );
          insert room;
      
        //Insert Customer
          Customer__c customer = new Customer__c(Gender__c = 'Male',First_Name__c ='Abhinav', 
                                                                                  Nationality__c ='Indian' );
           insert customer;
      
        // Insert Booking
         Booking__c booking = new Booking__c(room__c = room.id, Customer__c = customer.id,
                                                                           Status__c ='Check In');    
        //Start Test From Here
         test.startTest();
      
        try {
             insert booking;
           
        } catch (DmlException e) {
          
            //Assert Error Message
            System.assert( e.getMessage().contains('Insert failed. First exception on ' +
                'row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, ' +
                'Enter the Check In Time value'),
                e.getMessage() );
                
            //Assert field
            System.assertEquals(Booking__c.Check_In_Time__c, e.getDmlFields(0)[0]);
          
            //Assert Status Code
            System.assertEquals('FIELD_CUSTOM_VALIDATION_EXCEPTION' ,
                                 e.getDmlStatusCode(0) );
        }
    }
    static testMethod void myUnitTest1() {
  
         // Insert Room
          Room__c room = new Room__c(Rent__c=2000.00, Type__c='AC',Room_No__c='RN_121'; );
          insert room;
      
        //Insert Customer
          Customer__c customer = new Customer__c(Gender__c = 'Male',First_Name__c ='Abhinav',
                                                                                  Nationality__c ='Indian' );
           insert customer;
      
        // Insert Booking
         Booking__c booking = new Booking__c(room__c = room.id, Customer__c = customer.id,
                                                      Status__c ='Check In', Check_In_Time__c = system.Now());
      
         insert booking;
      
        //Start Test From Here
         test.startTest();
      
        //Asserting Results
            System.assertEquals(false, booking.Id == null);
    }
    static testMethod void myUnitTest2() {
        
  // Insert Room
          Room__c room = new Room__c(Rent__c=2000.00, Type__c='AC',Room_No__c='RN_121'; );
          insert room;
      
        //Insert Customer
          Customer__c customer = new Customer__c(Gender__c = 'Male',First_Name__c ='Abhinav', 
                                                                                  Nationality__c ='Indian' );
           insert customer;
      
        // Insert Booking
         Booking__c booking = new Booking__c(room__c = room.id, Customer__c = customer.id,
                                                         Status__c ='Check In', Check_In_Time__c = system.Now(),
                                                         Check_Out_Time__c = system.Now().addDays(2));
      
       //Start Test From Here
        test.startTest();
      
        try {
             insert booking;
           
        } catch (DmlException e) {
          
            //Assert Error Message
            System.assert( e.getMessage().contains('Insert failed. First exception on ' +
                'row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, ' +
                'if Status is Check in then Check out time Should not be there'),
                e.getMessage() );
                
            //Assert field
            System.assertEquals(Booking__c.Check_Out_Time__c, e.getDmlFields(0)[0]);
          
            //Assert Status Code
            System.assertEquals('FIELD_CUSTOM_VALIDATION_EXCEPTION' ,
                                 e.getDmlStatusCode(0) );
        }
    }
}

As illustrated you can you system.Assert in Test Classes.At Least 75% code coverage is required.

Sample Assertion Message




10 comments:

  1. Oh.. that's the one I am looking for improving my concept.

    ReplyDelete
  2. Nice Post. very Useful.

    ReplyDelete
  3. I have 3 batches and those names are 'batch-1 and batch-2 and batch-3' and is there any chance to execute all the 3-batches sequentially and how it is possible?

    ReplyDelete
  4. @Manideep, You can do this simply by calling Scheduler class in finish method of Batch class and then Scheduler will call the next batch.

    ReplyDelete
  5. thanks for reply and my doubt is implement the batch apex class and it having 3 batches and those batches must be automatically call when first batch is completed and then starts the 2nd and 3rd.In that situation with out using the schedule apex class.

    Is there any chance to send the basic example code.

    ReplyDelete
  6. Can give me any knowledge of web services and with brief examples of rest and soap api

    ReplyDelete
  7. I have 2 objects :Company(Master) and employee(detail) .
    when i am provide any private or public or any permission to company or employee but when i am click on owd edit option and those objects are not visible.

    go to the security controls and click on sharing settings and the list of objects are available, in that one the above objects are displayed by like this:
    company(controlled by parent)
    employee(controlled by parent)

    ReplyDelete
  8. @Manideep, Please refer the link given below for detailed explation of web services in Salesforce www.youtube.com/watch?v=QvwOcbuylZo

    ReplyDelete
  9. keep some light background difficult to read

    ReplyDelete
  10. Done. Set the background of light color.

    ReplyDelete