Assertions In A Mock Callout Test

Notice how you set the value in this field:

contact.Never_Bounce_Result__c = (String)results.get('results');

Does your mock ever set a results attribute? No. You need to add this attribute to your JSON map ('{"status" : "success", ...}').


The problem here is because of the way you are testing a future callout.

Because the updates are being carried out in a future method, thus while asserting, you don't get the value while you are asserting it between Test.startTest() and Test.stopTest(). Refer to this trailhead on how to test future methods, except below (emphasis mine).

The system collects all asynchronous calls made after the startTest. When stopTest is executed, all these collected asynchronous processes are then run synchronously. You can then assert that the asynchronous call operated properly.

So you will need to make the assertions in your test class, after Test.stopTest().

Test.startTest();
Test.setMock(HttpCalloutMock.class, new NeverBounceMock());    
NeverBounceCallout.checkNeverBounce(c.Id); 
Test.stopTest();

// assertion now
Contact contactToCheck = [SELECT Never_Bounce_Result__c FROM Contact WHERE Id =: c.Id LIMIT 1];
System.assertEquals('valid', contactToCheck.Never_Bounce_Result__c);

You will still need the below details to make sure your response returns correct value.


Your mock returns:

response.setBody('{"status" : "success", "result" : "valid"}');

and that you are trying to set the value of an attribute named results (notice the extra s here):

contact.Never_Bounce_Result__c = (String)results.get('results');

And thus your field Never_Bounce_Result__c would have never been set with the expected value here, thus failing your assertion.

For your assertion to work, you will need to set result as expected in the response and that it should be written as:

contact.Never_Bounce_Result__c = (String)results.get('result'); // no ending s here

Or, if you expect results, then that attribute needs to be set in the response accordingly.

Tags:

Apex

Rest Api