Short Answer:
Try calling both Batch X
and Batch Y
within the same testMethod
and perform assert after stopTest
.
Long Answer:
Here you are testing two batches X
and Y
.
Limitations:
- We cannot call Test.stopTest more than once in a Test class
- Without the stopTest call, asynchronous jobs will not run
Current Testing methodology:
Test Data Generation -> Call Batch X -> Call Batch Y -> StopTest and Assert -> End the test
Recommended Testing methodology:
Batch X test
Test 1 Data Generation -> Call Batch X -> StopTest and Assert -> End the test
Batch Y test
Test 2 Stub the resultant data of Batch X -> Call Batch Y -> StopTest and Assert -> End the test
Pros:
So by this you don't really rely on execution of Batch X, instead you have stubbed the data which would exactly mimic the effect of Batch X execution.
Introducing stubbed data makes your tests independent and also makes your input and output rigid.
In future if the Batch Z calls the Batch Y at end of its execution, you don't need to assert the every new possible flow again, since Batch Y specifies its own set of Pre-Conditions
You will be able to test individual components to the fullest granularity, and any breaking implementation changes in Batch X will not raise false assertion failures for Batch Y since both the tests are decoupled
Reference on Async Batch limitations:
The System.schedule method starts an asynchronous process. This means
that when you test scheduled Apex, you must ensure that the scheduled
job is finished before testing against the results. Use the Test
methods startTest and stopTest around the System.schedule method to
ensure it finishes before continuing your test. All asynchronous calls
made after the startTest method are collected by the system. When
stopTest is executed, all asynchronous processes are run
synchronously. If you don’t include the System.schedule method within
the startTest and stopTest methods, the scheduled job executes at the
end of your test method for Apex saved using Salesforce.com API
version 25.0 and later, but not in earlier versions.
https://salesforce.stackexchange.com/a/14550/3672
test.stopTest()
. Have you tried validating your data after that happens? – crmprogdev Feb 26 '16 at 19:30