I have a batch class that inserts Journal records after updating Account records... I am new to apex and cannot think how to test the inserted records in the test class. I have a list to get the journal records, can I do system.asserts inside a for loop? Feel like this is something I've not seen before...

1 Answer 1


Yes, you can do asserts in a for loop, if it makes sense. While it is rare to see examples of this on the Internet, there's nothing wrong with it.

For example, let's say I was testing a trigger that looked like this:

trigger setTimestamp on Account(before insert) {
  for(Account record: Trigger.new) {
    record.TimeStamp__c = System.now();

With a unit test like this:

@isTest static void testSetTimestamp() {
  Account[] accounts = new Account[0];
  while(accounts.size() < 100) {
    accounts.add(new Account(Name='Test '+accounts.size()));
  insert accounts;
  accounts = [SELECT TimeStamp__c FROM Account];
  for(Account record: accounts) {
    System.assert(record.TimeStamp__c != null);

Here, we make sure that all the time stamps are populated. While this is a contrived example, it is conceivable that you'd have a real-life pattern that would follow this same design.

Typically, you'd use System.assert/assertEquals/assertNotEquals in a loop where you're interested in confirming bulkified behavior.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .