Given the following batch code:
global without sharing class POCBatch implements Database.Stateful, Database.Batchable<Sobject>{
public static List<String> staticList = new List<String>();
public List<String> nonStaticList = new List<String>();
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator([Select Id from Account limit 1]);
}
global void execute(Database.BatchableContext BC, List<Sobject> scope) {
staticList.add('StaticAdd');
nonStaticList.add('NonStaticAdd');
}
global void finish(Database.BatchableContext BC) {
System.debug('finishStaticList: '+staticList);
System.debug('finishNonStaticList: '+nonStaticList);
}
}
and the following test method:
@isTest
private class POCBatchTest {
@isTest
static void testPOCBatch(){
insert new Account(Name = 'For Test');
POCBatch poc = new POCBatch();
Test.startTest();
Database.executeBatch(poc);
Test.stopTest();
System.debug('test method static list: '+POCBatch.staticList);
System.debug('test method non-static list: '+poc.nonStaticList);
}
}
If you run in a batch versus text context, it gives different results. In both case it is selecting a single Account from the org (but doesn't do anything with it).
Batch context debug output:
finishStaticList: ()
finishNonStaticList: (NonStaticAdd)
Test method debug output:
finishStaticList: (StaticAdd)
finishNonStaticList: (NonStaticAdd)
test method static list: (StaticAdd)
test method non-static list: ()
My questions are:
1) Why are there differences in the finish method output in the different contexts?
2) It appears that the static context is lost in the batch, but the non-static context is lost in the test method. So how can I test the list's contents in the batch's test method?