I have an apex trigger f_contactPushNotificationTrigger that should fire when a new contact is created. This trigger call f_PushNotification class used to Post data.
I used @future to make this task asynchronous Since the trigger makes HTTP callouts. Correct no?
The problem I am facing is creating a testing unit for the trigger and f_PushNotification class so I can deploy my code.
I have tried the Mock generation response (but the problem I am facing is that @future does not make it possible to return the response) and Test.StartTest() but both not working.
Below the error I got:
f_contactTriggerTest test Methods defined as TestMethod do not support Web service callouts Stack Trace: null
f_GetRelatedContactsId test Methods defined as TestMethod do not support Web service callouts Stack Trace: null
So it seems a conflict is happening with another trigger: f_GetRelatedContactsId that runs after insert on contact but does not have any HTTP callout.
So should I also stop this trigger for testing?
Could you please help me!
Trigger:
trigger f_contactPushNotificationTrigger on Contact (after insert)
{
for(contact con:trigger.new)
{
f_PushNotification.sendNotification(con.FirstName);
}
}
f_PushNotification:
public class f_PushNotification {
@future (callout=true)
public static void sendNotification(String text) {
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://---');
request.setMethod('POST');
request.setHeader('Content-Type', 'multipart/form-data;charset=UTF-8');
// Set the body as a JSON object
request.setBody('{"text":"'+text+'"}');
HttpResponse response = http.send(request);
// Parse the JSON response
if (response.getStatusCode() != 201)
System.debug('The status code returned was not expected: ' +
response.getStatusCode() + ' ' + response.getStatus());
else
System.debug(response.getBody());
}}
Tests:
@isTest
public class f_contactPushNotificationTest
{
@isTest static void testCallout()
{
Contact con = new Contact (FirstName = 'FnamePushNotification');
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
Test.startTest();
insert con;
Test.stopTest();
}
}
Testing documentation I followed:
Mock Generation:
@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
// Implement this interface method
global HTTPResponse respond(HTTPRequest req) {
// Optionally, only send a mock response for a specific endpoint
// and method.
System.assertEquals('https://forestsal.xyz/sendNotification.php', req.getEndpoint());
System.assertEquals('Post', req.getMethod());
// Create a fake response
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{"FirstName":"test"}');
res.setStatusCode(200);
return res;
}}