In a unit test class how can we verify that code didn't run or a DML statement wasn't executed because a condition wasn't met?

Contrived Example (Updated):

public static void DoStuff(List<Contact> contacts)

    if(contacts.size() == 0)
        // exit due to condition not met

    List<Id> contactsToFilter = new List<Id>();
    for(Contact c : contacts)


    List<Contacts> contactsWithoutFirstNames = 
                             [SELECT Id, Name 
                              FROM CONTACT 
                              WHERE Id in : contactsToFilter];

    DELETE contactsWithoutFirstNames;


In the code above I would like to verify that when an empty collection was sent in that we did not execute the loop or any additional code inside the DoStuff method.

Currently in my test class I'm asserting that the records passed in are unchanged but it requires a lot of test setup (inserting fake records, etc) just to assert that c.FirstName does not equal test later on. I considered adding a property to the class to keep track of records processed but that feels like a hack.

  • N.B. update contacts when the collection is empty does not burn any DML; and .. in the contrived example, testing for empty collection doesn't add to the consiseness/readability of the method once you realize that dml and for loops on empty lists are essentially NOP. That said, SOQL should be gated by empty checks.
    – cropredy
    Commented Oct 31, 2018 at 23:16

1 Answer 1


Short of using a variable to keep track of this, you can't, as you've observed. Additionally, there's no point in writing a unit test like that; using the if statement or not has practically no observable difference (about 0.02ms, according to my calculations). I would suggest not using the if statement simply because it makes code coverage easier.

  • Apologize if contrived example wasn't clear. Would your recommendation be the same if the if statement was there to guard against an operation inside the loop that could throw an exception if the list was empty?
    – zhx
    Commented Oct 31, 2018 at 23:31
  • @zhx Iterating over an empty list won't execute any of the code in the loop. Yes, there are some times when you need to guard against empty lists, but they're not nearly so fragile as one might think.
    – sfdcfox
    Commented Nov 1, 2018 at 0:02
  • @zhx Just saw you made an edit. The only thing I'd change from that point to check if the contactsToFilter list was empty; there's no point in wasting a query when you know there's no results. To that end, in that case, you could verify the SOQL limits to verify that they have not changed. Do avoid wasting "valuable" resources like SOQL statements and such, but don't fret small optimizations, like your original code.
    – sfdcfox
    Commented Nov 1, 2018 at 0:08

You must log in to answer this question.

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