0

We can only test classes with mock callouts but cannot do a callout directly from a test class. (If we do test class fails). Is there a reason?

1 Answer 1

3

The reason is, as any good unit testing framework would require, to ensure that the unit tests are not reliant on any external resources. Unit tests should be entirely self-sufficient.

You don't want your tests failing simply because the external system that your callout invokes is temporarily unavailable from the Salesforce org, for example.

The unit test is testing your code, not the external resource.

UPDATE: As commented by sfdcfox, you also don't want your unit tests potentially modifying live data (if your callout effects change in the external service).

3
  • 3
    +1 Though, there's a second reason: allowing a callout would allow a unit test to modify live data, which is against best practices for unit testing. Unit tests should never be able to modify live data.
    – sfdcfox
    Dec 2, 2019 at 13:12
  • Speed is also an important consideration. Callouts take a long time relative to the rest of the processing time. But otherwise the risk of callouts creating/modifying real data and then not being able to roll it back is why why use mocks. Dec 2, 2019 at 21:32
  • Speed could be a consideration, but I think this is not relevant when you consider the primary reasons you just shouldn't be able to use a real callout in a unit test, as already described. After all, a unit test simply should not be testing the callout service, but rather that the callout service is correctly invoked and the response is correctly handled. (To test that the callout service functions requires a systems integration test, not a unit test.)
    – Phil W
    Dec 2, 2019 at 21:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .