I am writing a batch apex call which seems to functioning correctly, however when I attempt to create a test class for it I keep getting a null pointer exception when I query for the object that is supposed to be created during the execute method. However when I make the same query WITHIN the execute method following the insert of this new record with the test query commented out it finds the record just fine. I'm thinking it has something to do with batch jobs running asynchronously because the query seems to be running before the execute method even starts, any ideas how to make the batch run synchronously?
@isTest static void executeTest() {
Account storeAccount = TestDataFactoryStatic.createStoreAccount('Twin Cities');
Id storeAccountId = storeAccount.Id;
Id storeConfigId = storeAccount.Active_Store_Configuration__c;
Id accountId = TestDataFactoryStatic.createAccount('Calvins', storeAccountId).Id;
Contact primaryContact = TestDataFactoryStatic.createContact(accountId, 'CalvinPrime');
Contact secondaryContact = TestDataFactoryStatic.createContact(accountId, 'CalvinSec');
Opportunity opportunity = TestDataFactoryStatic.createNewOpportunity('Calvins Opportunity', accountId, storeAccountId, 'Sold', date.today());
OpportunityContactRole oppContJunc = TestDataFactoryStatic.createOppCon('Decision Maker', true, primaryContact, opportunity);
Order order = TestDataFactoryStatic.createOrderTestRecords(opportunity);
Id orderId = order.Id;
Id workOrderId = TestDataFactoryStatic.createWorkOrder(orderId, accountId, opportunity).Id;
Id resourceUserId = TestDataFactoryStatic.createResourceUser('RMS Field Service Partner').Id;
Id scheduledResourceId = TestDataFactoryStatic.createResource(resourceUserId, 'Calvins Installers','Install Crew', storeConfigId).Id;
Id assignedResourceId = TestDataFactoryStatic.createAssignedResource(workOrderId, scheduledResourceId).Id;
Test.startTest();
BatchJobPostInstallationSurvey obj = new BatchJobPostInstallationSurvey();
Database.executeBatch(obj);
Survey__c newSurvey = [SELECT Id, Primary_Contact_First_Name__c, Opportunity__c, Installation_Date__c, Order_Name__c FROM Survey__c LIMIT 1];
system.assertEquals(newSurvey.Primary_Contact_First_Name__c, 'CalvinPrimeTest');
Test.stopTest();
}
the null pointer exception occurs directly after the line Database.executeBatch(obj);
TestDataFactoryStatic
?newSurvey
is null? Put Debugs in your Batch and see if everything is qualifying correctly