Salesforce Apex: Using System.Assert()

When developing a Test class in Salesforce, System.Assert enables you to test your assumptions about your code. This is useful to verify the business logic in the Apex Classes you have created.

 

 

Similar to Java, the assertion will cause an exception in Salesforce. Normally, we will not use it on Trigger or Apex class but it is a good practice to include it in the Test Class. A Test class without the proper Assertion is considered as a smoke test if you run through Salesforce security review.

 

 

Let me show you an example below how the assertion can be implemented:

 

 

 

Scenario: Create Test Products

 

List prodList = new List();
        
String productName = 'Readymade Inventory Test Product ' + batch;
        
for(Integer i = 0; i < 5; i++) {
  Product2 prod = new Product2();
  prod.Name = productName + i;
  prod.productCode = '00' + i; 
  prod.isActive = true;
  prod.Quantity_On_Hand__c = 50;
  prodList.add(prod);
}

insert prodList;
        
List insertedProductList = [select Id, Name, productCode, isActive, Quantity_On_Hand__c From Product2 where Name like: productName + '%'];

// The assertion goes here. If the end result does not create 5 products, you will see the assertion error "Fail to create product"
System.assert(insertedProductList.size() == 5, 'Fail to create product!');