1

What is the use of mock callouts in Apex?

They are used for testing purposes, because it is impossible to perform a callout in method annotated with @isTest. And because it is necessary to have test coverage of at least 75% of all the code in org which includes the code which performs callouts and the coverage should pass with 100% score. Ok, that is clear for me.

But what benefit are you getting from writing two equal values manually (the first one is a return value of a mock method and the second one is the value you are expecting) and then making sure that they are really the same (when you know they are)? That does not make sense for me at all. Would not it be better to just exclude the code which performs callouts from those 100% out of which 75% should be covered?

7

If your mock does return similar data to the real web service, then your tests can assert that your code that processes the response works correctly. You can also make the mock assert that you send the right request data out to the web service.

Setting up a mock means you don't have to add a Test.isRunningTest() in your product code: changing the code under test just to test it is best avoided.

If your code does no processing on the returned data then you are right it is a fairly pointless exercise.

The main value of unit tests is that they check your implemented logic, and if you use Continuous Integration they can get run many times a day and alert you if when making one change you have broken existing logic. Coverage is just one measure of how well your tests are doing and is not a goal in itself. Personally I target 90% coverage overall.

5

Even if you're just returning whatever your mock returns, it can still be beneficial to set up a mock. It can help catch regression errors, like if someone introduces some code that causes a DML before the callout, your unit test would catch that scenario by failing (you're not allowed to callout after a DML statement). The assertion may be pointless, but the effort of covering the production code itself is not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.