2

I am a bit new to development, but I have a apex rest web service class in my org that people can make calls to. However im not quite sure how to write test classes for this class to ensure 75% score. I have read a bit on the doc on how to do that but Im confused.

Could someone please assist on how I could do the test on this code:

@RestResource(urlMapping='/cs/api/v1/*')
global with sharing class RESTCandidateSourcingManagementService {  
    @HttpPost
    global static Id postData() {       
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        Id returnId;        
        //Determine which function to perform based on URI
        String URI = req.requestURI.substring(req.requestURI.lastIndexOf('/') + 1);     
        if (URI.equals('candidate')) {
            String jid = req.params.get('jid');
            System.debug(req.params.get('jid'));
            if (jid != null) {
                //Post new candidate
                returnId = postCandidate(jid, req);
            }
        } else
        if (URI.equals('jobRequisition')) {
            //Post new jobRequisition
            returnId = postJob(req);
        }
        return returnId;        
    }

    public static Id postCandidate(String jid, RestRequest restRequest) {
        System.debug('>>>Begin processing Candidate request');
        RestRequest req = restRequest;      
        String JSONBody = req.requestBody.toString();
        //Variables
        PCandidate c;
        Contact contact; Job__c job; Qualification__c qualification; Candidate__c candidate; 
        Job_Requisition__c jobRequisition;
        if (JSONBody.startsWith('{')) { 
            System.debug('>>>Request is valid');    
            JSONBody = JSONBody.replace('"currency"', '"currency_x"');
            JSONParser parser = JSON.createParser(JSONBody);    
            while (parser.nextToken() != null) {            
                if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
                    if (parser.getCurrentName() == null) {
                        c = (PCandidate)parser.readValueAs(PCandidate.class); 
                    }           
                }               
            }
            if (c != null) {
                try {
                    System.debug('>>>Creating Candidate');
                    contact = new Contact(
                        contactType__c = 'Candidate',
                        id__c = c.id, Email = c.email, Salutation = c.title, FirstName = c.fName, 
                        MiddleName = c.mName, LastName = c.lName, maidenName__c = c.maidenName, 
                        Birthdate = c.getDob(), gender__c = c.gender, idNumber__c = c.idNumber, 
                        passportNumber__c = c.passportNumber, race__c = c.race, nationality__c = c.nationality, 
                        about__c = c.about, interests__c = c.interests, MailingStreet = c.location.street1 + ', ' 
                        + c.location.suburb, MailingCity = c.location.city, MailingState = c.location.province, 
                        MailingPostalCode = c.location.postalCode, MailingCountry = c.location.country, Phone = c.tel, 
                        MobilePhone = c.cell, careerObjectives__c = c.careerObjectives, 
                        currentEmployer__c = c.currentJob.employer, currentPosition__c = c.currentJob.position, 
                        highestQualification__c = c.highestQualification, skills__c = c.stringSkills(), 
                        personality__c = c.stringPersonality(), languages__c = c.stringLanguagesPicklist(), 
                        seekingPositions__c = c.seeking.stringPositions(), seekingType__c = c.seeking.type, 
                        seekingSalaryCurrency__c = c.seeking.salary.currency_x, 
                        seekingSalaryAmount__c = Decimal.valueOf(c.seeking.salary.amount), 
                        seekingSalaryType__c = c.seeking.salary.type, relocation__c = Boolean.valueOf(c.relocation), 
                        facebook__c = c.social.facebook, twitter__c = c.social.twitter, linkedIn__c = c.social.linkedIn, 
                        gtalk__c = c.social.gtalk, skype__c = c.social.skype, homepage__c = c.homepage, 
                        blog__c = c.blog, foreign__c = Boolean.valueOf(c.foreign), 
                        driversLicense__c = Boolean.valueOf(c.driversLicense), disabled__c = Boolean.valueOf(c.disabled), 
                        achievements__c = c.achievements, noticePeriodNumber__c = c.noticePeriodNumber(), 
                        noticePeriodType__c = c.noticePeriodPeriod(), source__c = c.source
                    );
                    insert contact;
                    System.debug('>>>Created ' + contact);
                    if (contact != null) {
                        System.debug('>>>Creating Job History');
                        if (c.jobHistory != null) {
                            for (Integer i = 0; i < c.jobHistory.size(); i ++) {
                                try {
                                    job = new Job__c(
                                        contact__c = contact.Id,
                                        employer__c = c.jobHistory[i].employer,
                                        position__c = c.jobHistory[i].position,
                                        industry__c = c.jobHistory[i].industry,
                                        type__c = c.jobHistory[i].type,
                                        fromDate__c = c.jobHistory[i].getFromDate(),
                                        toDate__c = c.jobHistory[i].getToDate(),
                                        current__c = Boolean.valueOf(c.jobHistory[i].current),
                                        duties__c = c.jobHistory[i].duties,
                                        reasonForChange__c = c.jobHistory[i].reasonForChange
                                    );
                                    insert job;
                                    System.debug('>>>Created ' + job);
                                } catch (DmlException e) {
                                    for (Integer j = 0; j < e.getNumDml(); j ++) {
                                        System.debug(e.getDmlMessage(i));
                                    }
                                }
                            }
                        }                   
                        if (c.qualifications != null) {
                            System.debug('>>>Creating Qualifications');                 
                            for (Integer k = 0; k < c.qualifications.size(); k ++) {
                                try {
                                    qualification = new Qualification__c(
                                        contact__c = contact.Id,
                                        institution__c = c.qualifications[k].institution,
                                        achievement__c = c.qualifications[k].achievement,
                                        degreeLevel__c = c.qualifications[k].degreeLevel,
                                        achieved__c = c.qualifications[k].getAchieved(),
                                        current__c = Boolean.valueOf(c.qualifications[k].current)
                                    );
                                    insert qualification;
                                    System.debug('>>>Created ' + qualification);
                                } catch (DmlException e) {
                                    for (Integer l = 0; l < e.getNumDml(); l ++) {
                                        System.debug(e.getDmlMessage(l));
                                    }
                                }
                            }
                        }                   
                        System.debug('>>>Creating Candidate');
                        try {
                            candidate = new Candidate__c(
                                candidate__c = contact.Id,
                                Job_Requisition__c = [SELECT Id FROM Job_Requisition__c WHERE nid__c =: jid].Id
                            );
                            insert candidate;   
                            System.debug('>>>Created ' + candidate);        
                        } catch (DmlException e) {
                            for (Integer m = 0; m < e.getNumDml(); m ++) {
                                System.debug(e.getDmlMessage(m));
                            }
                        }
                    }
                } catch (DmlException e) {
                    for (Integer n = 0; n < e.getNumDml(); n ++) {
                        System.debug(e.getDmlMessage(n));
                    }
                }                   
            }
        } else {
            System.debug('>>>Request is invalid');
        }
        return contact.Id;
    }

    public static Id postJob(RestRequest restRequest) {
        System.debug('>>>Begin processing Job Requisition request');
        RestRequest req = restRequest;      
        String JSONBody = req.requestBody.toString();
        //Variables
        Job_Requisition__c jobRequisition; PJobRequisition j;
        if (JSONBody.startsWith('{')) {
            System.debug('>>>Request is valid');        
            JSONBody = JSONBody.replace('"currency"', '"currency_x"');
            JSONParser parser = JSON.createParser(JSONBody);                
            while (parser.nextToken() != null) {            
                if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
                    if (parser.getCurrentName() == null) {
                        j = (PJobRequisition)parser.readValueAs(PJobRequisition.class);
                        System.debug('Created ' + j);
                    }
                }
            }
            if (j != null) {
                System.debug('>>>Creating Job Roquisition');
                try {
                    jobRequisition = new Job_Requisition__c(
                        nid__c = j.id,
                        title__c = j.title,
                        reference__c = j.reference,
                        mxit__c = j.booleanMxit(),
                        position__c = j.position,               
                        industry__c = j.industry,
                        bee__c = j.bee,
                        type__c = j.type,
                        available__c = j.booleanAvailable(),
                        city__c = j.location.city,
                        province__c = j.location.province,
                        country__c = j.location.country,
                        description__c = j.description,
                        responsibilities__c = j.responsibilities,
                        experience__c = j.experience,
                        qualifications__c = j.stringQualifications(),
                        languages__c = j.stringLanguagesPicklist(),
                        skills__c = j.stringSkills(),
                        personality__c = j.stringPersonality(),
                        requirements__c = j.requirements,
                        department__c = j.department,
                        salaryType__c = j.salary.type,
                        salaryAmount__c = j.salary.decimalAmount(),
                        salaryCurrency__c = j.salary.currency_x,
                        benefits__c = j.stringBenefits(),
                        incentives__c = j.incentives,
                        requisition__c = j.requisition
                    );
                    insert jobRequisition;  
                    System.debug('>>>Created ' + jobRequisition);       
                } catch (DmlException e) {
                    for (Integer i = 0; i < e.getNumDml(); i ++) {
                        System.debug(e.getDmlMessage(i));
                    }
                }
            }
        } else {
            System.debug('>>>Request is invalid');
        }
        return jobRequisition.Id;
    }
}

I have used the docs and have produced something but I see in the code coverage section I have 0% for the class above. Below is my code:

My MockHttpResponseGenerator Class

@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://pfdev.envisionme.co.za/api/v1/candidate', req.getEndpoint());
        System.assertEquals('POST', req.getMethod());

        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"foo":"bar"}');
        res.setStatusCode(200);
        return res;
    }
}

My Callout Class

public with sharing class CalloutClass {
    public static HttpResponse getInfoFromExternalService() {
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://pfdev.envisionme.co.za/api/v1/candidate');
        req.setMethod('POST');
        Http h = new Http();
        HttpResponse res = h.send(req);
        return res;
    }
}

My CalloutClassTest Class

@isTest
private class CalloutClassTest {

    static testMethod void testCallout() {
        // Set mock callout class 
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());

        // Call method to test.
        // This causes a fake response to be sent from the class that implements HttpCalloutMock. 
        HttpResponse res = CalloutClass.getInfoFromExternalService();

        // Verify response received contains fake values
        String contentType = res.getHeader('Content-Type');
        System.assert(contentType == 'application/json');
        String actualValue = res.getBody();
        String expectedValue = '{"foo":"bar"}';
        System.assertEquals(actualValue, expectedValue);
        System.assertEquals(200, res.getStatusCode());
    }
}
0
1

While the http response mock is used for webservices, it is used in the opposite scenario where salesforce is consuming services from another site. Rather than have the test send out a request to that site and use an actual response, the mock can simulate the process and provide a response directly without sending out the request.

In your situation, where salesforce is providing the service, you want the test to simulate a request being received. Your tests will need to include something like this:

System.RestContext.request = new RestRequest();
RestContext.request.requestURI = '/cs/api/v1/*';
RESTCandidateSourcingManagementService.postData();
2
  • Hello Martin, I believe I made a mistake with my post, Im actually referring to a callout class with future annotations. Please take a look at my edit Aug 29 '15 at 12:23
  • So, how is the RESTCandidateSourcingManagementService class related to the callout class?
    – martin
    Aug 29 '15 at 13:51

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.