Salesforce Apex: test that callout hasn't been

2019-09-03 13:21发布

问题:

I want to write a unit test that checks that callout hasn't been made from the trigger.

I know how to test if the callout is made correctly - by implementing HttpCalloutMock:

global class MyHttpCalloutMock implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest req) {
        //test HTTPRequest here
    }
}

But if no HTTP request is made, then the respond() method won't be called. So this approach doesn't test if the request was made at all.

I need something like this:

HTTPRequest.assertNoRequestsHaveBeenMade();

How do I do that?

回答1:

So I figured it out. It turns out that Salesforce has methods Test.startTest() and Test.stopTest() that make asynchronous callouts synchronous: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_tools_start_stop_test.htm

After making callouts synchronous it's much easier to test them.