When ik create a list, set or map and add records to these do I need to update / insert after adding records. I did a test system debug on a testclass with only a return.

My debug returns a list with Ids, but I want to make shure I understand the concept

 public static List<Account> createAccounts(Integer numAccts) {        
        List<Account> accList = new List<Account>();

at this point isnt accList empty? as accList = null?

    for(Integer i=0;i<numAccts;i++) {
        Account a = new Account(Name='TestAccount' +'-'+ i);

Do I not need to update or insert accList as a dml action at this point or is the a difference with a class or testclass?

return accList;

2 Answers 2


Your code is correct, but you still need to run the DML action to insert the list of Accounts to the database, to be able then to perform other selection queries for testing purposes or if you are simply writing an Apex class.

To do that (in a test class), you need to run

insert accList;

after the for loop.

You may want to use the Database class to handle the database action results after running the dml operation in a test class.

  • Thanks, but in the testclass does the dml operation get rolled back a later point in testclass and if I add more record to the list do I have to perform an update on the list intestclass to be able to query the results?
    – Thomas
    Sep 27, 2018 at 10:16
  • In a test class you can define your dml actions in between Test.startTest() and Test.endTest() methods, all dml operations won't commit, so you won't need to delete anything after the tests. (Please refer to this doc: developer.salesforce.com/docs/atlas.en-us.apexcode.meta/… )
    – Alberto
    Sep 27, 2018 at 10:20
  • I've updated the answer.
    – Alberto
    Sep 27, 2018 at 10:22
  • You can refer also to this trailhead where it's better explained with examples when you should use Test.startTest(): trailhead.salesforce.com/modules/apex_testing/units/…
    – Alberto
    Sep 27, 2018 at 10:24
  • I've edited again the answer with a reference to the Database class that would help you checking the results of the dml operations after running them.
    – Alberto
    Sep 27, 2018 at 10:26

Yes you need to create data so that your query can fetch them and perform the calculation in code.

Get Started with Apex Unit Tests

I suggest you to check this trailhead module to get better understanding of test class and apex testing.

  • Thanks already did this trailhead. In this case there is no insert to the database.
    – Thomas
    Sep 27, 2018 at 10:13

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.