You can combine the callout and the DML in the same method if you want to; the only restriction is that no callouts are allowed after a DML. Each call to start, execute, and finish are separate transactions. There's really no need to perform your DML in the finish method, as you can do so in the execute method. Notably, if you're trying to do more than 10,000 callouts before you finally write to the database, you'll exceed the DML limit.
Your current design would certainly work, assuming the OAuth token doesn't expire until the end of the batch. Personally, I'd recommend moving the OAuth check into the execute method so that if you lose your token half-way through (say, because it's revoked), your batch can recover. You may also want to increase your scope size from 1 to a larger number, depending on how much callout time you think you'll need.
To calculate how many callouts you can do, figure out how much time is needed for each callout, and divide that into the maximum callout time. For example, if your callout takes an average of 5 seconds, then your limit would be 60 callouts in a transaction. Of course, you can't go over the governor limit of 100, so that'd be your maximum value.
Finally, batchable Apex isn't scheduled Apex, even though both are a form of "asynchronous" Apex. You won't need to worry about that error, even if you're chaining, and even if you use scheduleBatch to insert a delay inbetween.
Yes, you can, using either of two techniques.
Your HttpCalloutMock
's respond()
method can inspect its inbound HttpRequest
, and construct a different response based on which endpoint is being called, the parameters passed, etc. This allows you to write a single class that returns responses for multiple callouts made in sequence in your code under test.
Alternately, you can choose to use the MultiStaticResourceCalloutMock
class. This class allows you to store response bodies in Static Resources within your application, and to configure the Mock for multiple endpoints by calling setStaticResource()
once per endpoint to which you wish the Mock to respond. This can save you writing some boilerplate code, if you don't mind storing your responses in Static Resources rather than constructing them in code.
Best Answer
You can have more than one callout in a test class. Check the Salesforce developer blogs for examples. This one looks like what you need.
https://developer.salesforce.com/blogs/developer-relations/2012/10/testing-http-callouts-with-static-data-in-winter-13.html
Copying code here for your convenience