Activity Forums Salesforce® Discussions What is the use of System.assertEquals() in Salesforce?

  • Anurag

    Member
    July 30, 2018 at 11:13 am

    Hi Avnish,

    We use System.assertEquals in our test methods basically to check whether the two values are equal or not.One of the value is said to be expected value which we expect while making dummy variables and giving values to it. The second is the actual result which we get on passing the variable in the given class method. System.assertEquals() returns true if the values are equal and throws an exception message(which is also provided by us) in case they are unequal.

  • shradha jain

    Member
    September 17, 2018 at 9:57 am

    Hi Avnish,

    System.assertEquals() is used to validate two values are equal. Basically it is used in test method. This method asserts that the first two arguments, x and y are the same, if they are not a runtime exception is thrown.

    Example:

    Account ac=new Account(name=’testName’);

    Insert ac;

    Account acc=[select id,name from account where id=:ac.id];

    System.assertEquals(acc.name, ‘testName’);

  • shariq

    Member
    September 17, 2018 at 5:48 pm

    Hi,

    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.

    example -

    static testMethod void runNegativeTestCases(){
    User u3 = [select id from User where alias='tuser'];
    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 testMiles3;

    }catch (DmlException e){

    //Assert Error Message

    System.assert( e.getMessage().contains('Insert failed. First exception on ' +'row 0; first error:FIELD_CUSTOM_VALIDATION_EXCEPTION,'+'Mileage request exceeds daily limit(500): [Miles__c]'),e.getMessage() );

    //Assert field

    System.assertEquals(Mileage__c.Miles__c, e.getDmlFields(0)[0]);

    //Assert Status Code

    System.assertEquals('FIELD_CUSTOM_VALIDATION_EXCEPTION' , e.getDmlStatusCode(0) );

    } //catch

    } //RunAs(u3)

    Hope this helps.

  • Parul

    Member
    September 17, 2018 at 6:02 pm

    Hi

    System.assertEquals() asserts that the first two arguments are the same. if they are not same, a fatal error is returned that causes code execution halt.

    Signature of this method:
    Public static void assertEquals(Object expected, Objecet actual, object msg)

    This method is having three parameters, one is expected which is a type of object, second one is actualwhich is also type of object and the other one msg which is optional and type of object.

     

    Thanks

Log In to reply.

Popular Salesforce Blogs