function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
kyasukyasu 

How to avoid/exclude existing records in testMethod

hi,

I writeing a testMethod for "Batch class".

I want to test "Batch class" with only "test data created in testMethod".

But existing records are tested too when execute test.

 

I want to test only "test data".

 

How to code testMethod ?

bob_buzzardbob_buzzard

I usually have a Boolean property in "batch class" called testMode that defaults to false.  if testMode is true, the query is changed as required (only pick up test records, limit to 500 records returned etc).   Then when my test instantiates the batch class, it sets the testMode property to true.

Jeremy_nJeremy_n

Another simple option is (depending on how much existing data you have) to query for it in your testmethod, then delete all the records. For example, if your Batch runs on Account objects, you can do this:

 

 

static testmethod void testbatch()
{
   list<Account> existingaccs = [select id from Account];
   delete existingaccs; //there are no more accounts in the org now
   
   Account testingacc = new Account();
   insert testingacc;

test.startTest();
   BatchClass bc = new BatchClass();
   Database.executeBatch(bc,10);
test.stopTest();
}

 

Of course, this only works if you know you aren't going to run into governor limits. If you have more than 10000 records, you'll have to do something more complex.

 

Jeremy

kyasukyasu

bob, Jeremy   Thank you.

 

these way are nice