I am writing an after insert, after update trigger for a custom object CustomA_c. On changing the status field of this custom object to some value I need to create another custom object CustomB_c and insert it.

 trigger triggerOnObj on CustomA__c (after insert, after update) {

    List<CustomA__c> listOfCustomA = [select field1,field2 from CustomA__c where Status__c = 'picklist value'];

    List<CustomB__c> listOfCustomB = new List<CustomB__c>();

    for(CustomA__c customObj: listOfCustomA) {
       CustomB__c customB = new CustomB__c();
       //some other trigger related code
    insert listOfCustomB;

Both the custom objects A and B are unrelated. They do not have look-up to one another. My problem is when writing a test method/class for this trigger, how do I check if the for loop did inserted that many new B custom objects.


By default, your test class does not see any of the other data in your org, so any CustomObjectB that are inserted will be the only ones there. Once you insert CustomObjectA in your test class, you can SOQL for CustomObjectB and do as follows.

List<CustomB__c> listOfCustomB = [SELECT Id FROM CustomB__c];
System.assertEquals(3, listOfCustomB.size()); //If you think 3 should have been inserted

Let me start by saying that ideally you should be able to select your record with where clause criteria, a foreign key being the most bombproof. In the absence of that however, you still have options.

After API version 24.0 or later, unit test data is by default isolated to your test transaction and organization records are not visible. Therefore, even if you don't have a foreign key to use in the WHERE clause of your objectB SOQL, you should only return the records created in your test. If your "unrestricted" query returns no objectB records, then you know that your trigger code has failed but if it returns a record, you can be assured that it was the record that was created as a result of that test method.

Incidentally, you have control over this as a developer, whether you want to open up or isolate test data. You can annotate your testMethod with the boolean seeAllData = true/false. More information on test data isolation here:

Isolation of Test Data from Organization Data in Unit Tests

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.