+ Start a Discussion
Frank Jordan 14Frank Jordan 14 

Webservice Test Class help?

I am pretty new to Salesforce development and I am having a hard time wiriting a test class for some code that I am writing for a Jira to Salesforce connector. Below is my class and trigger, but I am not sure how to write a test class for a web service callout. Any help would be appreciated.

Class: 
global class JIRAWebserviceCalloutSyncStatus {
    @future (callout=true)
    WebService static void syncstatus(String status, String jiraKey) {
        //Modify these variables:
        String username = 'salesforceconnector';
        String password = 'xxxxxx';
        String jiraURL = 'https://xxxxx.xxxxxx.com';
        String transitionId;
         
        //Map Salesforce Status to JIRA transition Id:
         if (status == 'Waiting on Risk') {                  // Salesforce.com Status
            transitionId = '181';                 // JIRA transition ID
        } else if (status == 'Waiting on Customer') {
            transitionId = '21';
        } else if (status == 'Active') {
            transitionId = '161'; 
        } 
        
         
        //Construct HTTP request and response
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
 
        //Construct Authorization and Content header
        Blob headerValue = Blob.valueOf(username+':'+password);
        String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
        req.setHeader('Authorization', authorizationHeader);
        req.setHeader('Content-Type','application/json');
 
        //Construct Endpoint
        String endpoint = jiraURL+'/rest/api/2/issue/'+jiraKey+'/transitions';
         
        //Set Method and Endpoint and Body
        req.setMethod('POST');
        req.setEndpoint(endpoint);
        req.setBody('{ \"transition\": {\"id\": \"'+transitionId+'\"}}');
 
        try {
            //Send endpoint to JIRA
            res = http.send(req);
        } catch(System.CalloutException e) {
            System.debug(res.toString());
        }
    }
}

Trigger:
trigger SyncStatus on Case (after update) {
    //Identify profile name to be blocked from executing this trigger
    String JIRAAgentProfileName = 'JIRA Agent';
    List<Profile> p = [SELECT Id FROM Profile WHERE Name=:JIRAAgentProfileName];
     
    //Check if specified Profile Name exist or not
    if(!p.isEmpty())
    {
        //Check if current user's profile is catergorized in the blocked profile
        if(UserInfo.getProfileId()!= String.valueOf(p[0].id))
        {
            for (Case c : Trigger.new) {
                //Define parameters to be used in calling Apex Class
                String status = c.Status;
                String jiraKey = c.JIRA_Key__c;
                 
                JIRAWebserviceCalloutSyncStatus.syncstatus(status, jiraKey);
            }
        }
    }
}

Test Class:
 
@isTest
public class TestJIRAWebserviceCalloutSyncStatus {

    static testMethod void TestJIRAWebserviceCalloutSyncStatus(){
        Test.startTest();
        JIRAWebserviceCalloutSyncStatus.SyncStatus();
        Test.stopTest();
         
        
        
    }
    
    
    
}

 
Best Answer chosen by Frank Jordan 14
Greg HGreg H
Fake the response from the webservice if you are in testing context. Update line 41 in your global class to something like:
if (!Test.isRunningTest()) { //if we are not in testing context
	res = http.send(req); //grab the API response
} else { //otherwise, we are testing
	res.setBody('{"fake": "response"}'); //fake the response body
	res.setStatusCode(200); //denote status code of 200 Success
}

 

All Answers

Greg HGreg H
Fake the response from the webservice if you are in testing context. Update line 41 in your global class to something like:
if (!Test.isRunningTest()) { //if we are not in testing context
	res = http.send(req); //grab the API response
} else { //otherwise, we are testing
	res.setBody('{"fake": "response"}'); //fake the response body
	res.setStatusCode(200); //denote status code of 200 Success
}

 
This was selected as the best answer
Frank Jordan 14Frank Jordan 14
This works!!! Thank you so much!! Much appreciated
Martijn SchwarzerMartijn Schwarzer
Hi Frank,

I know you have a working solution, but there is a best practice for this scenario. For future reference, please take a look at the following article:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing.htm

It will keep your code clean (you cannot cover your actual callout in the test now) and keeps all testing logic in one place.

Happy coding!

Best regards,
Martijn Schwärzer