We are facing couple of issue with Unit Test methods.
- SOQL queries limit hits before "Test.StartTest()". We want to test a batch process and it needs to creates records for around 8 to 10 objects which has triggers. Because of that it is throwing limit exception before "Test.StartTest()".
Below is example of code.
@isTest
private class Test_Trigger_Contact
{
static testMethod void test1()
{
Student__c studentToAdd;
List<Contact> contacts= new List<Contact>();
// To create Test data we are creating some test records of around 8-10 objects.
// Internally it fires trigger and consumes diffrent SOQL queries, which cross 101 SOQL limit.
// Because of this our test class fails before "Test.StartTest()"/"Test.StopTest()".
for(integer i=0;i<101;i++)
{
contacts= [SELECT Id,Name FROM Contact];
}
test.startTest();
// Do Some Unit Test for a batch process
test.stopTest();
}
}
- Another problem is, Salesforce is not resetting the Governor limit inside "Test.StartTest()" and "Test.StopTest()". Which is mentioned on below Salesforce issue.
https://success.salesforce.com/issues_view?id=a1p30000000T5R5AAK
With below example, you can reproduce this issue :
@isTest
private class Test_Trigger_Contact
{
static testMethod void test1()
{
Student__c studentToAdd;
List<Contact> contacts= new List<Contact>();
// Below code is consuming 98 queries to generate Test Data
for(integer i=0;i<98;i++)
{
contacts= [SELECT Id,Name FROM Contact];
}
// After that we are using "test.startTest()", to reset governer imit.
// But it doesn't and throws 101 SOQL query error.
test.startTest();
// Do Some Unit Test for a batch process
for(integer i=0;i<3;i++)
{
contacts= [SELECT Id,Name FROM Contact];
}
test.stopTest();
}
}
2nd issue will be fixed with Salesforce release as mentioned on above link.
I am not sure how can we fix 1st issue. Where we need to generate large data to test Batch Process. My understanding was, Salesforce calculates governor limits only inside "Test.startTest()" and "Test.stopTest()" for unit Test method and it doesn't calculates it while generating test data. Can someone please confirm my understanding regarding?
Thanks and Regards, Ashish Shukla
Test.startTest()
should give you a new set of governor limits, but that does not mean that anything before it is ignored. I don't have the source to prove that ATM though