Tuesday, 15 November 2022

New Salesforce Assert Class

 Using Assertion.Fail() to intentionally return a fatal error.

Using Assertion.isInstanceOfType() to assert object instance.


ex : 


try {

    Test.startTest();

    SomeClass.someMethod();

    System.Assert.Fail('Throw custom exception);

 } catch (Exception baseException) {

     System.Assert.isInstanceOfType(baseException, 

                                   SomeClass.SomeCustomException, 

                                   'Expected an instance of SomeCustomException');

 }

  

Using Assert.isNull() to assert the null values.


 ex :  

  Opportunity opp = OpportunityService.getRecentClosedOpportunity();

  System.Assert.isNotNull(opp, 'Expected the opportunity to not be null'); 

  System.Assert.isNull(calloutResponse, 'Expected a null response');


Using Assert.areEqual() instead of System.assertEquals() for clarity.


ex : 


Account acc = new Account();

acc.Name = 'Test Account';

insert acc;

System.Assert.areEqual('Test Account', acc.Name, 'Expected account name to be Test Account');


String sub = 'abcde'.substring(2);

System.Assert.areNotEqual('xyz', sub, 'Characters not expected after first two');


Using Assert.isTrue() instead of System.assert() for clarity.


ex:   

  

Boolean containsForce = 'Salesforce'.contains('force'); 

System.Assert.isTrue(containsForce, 'Expected true result.');

System.Assert.isFalse(containsForce,'Expected false result.');

System.Assert.isTrue(insertResults.isEmpty());


Note :


Write System.Assert.areEqual instead of Assert.areEqual and you can safely use the new classes.

No comments:

Post a Comment