Sample Inbound REST API Test Class in Salesforce

Sample Inbound REST API Test Class in Salesforce

Sample REST Class:

@RestResource(urlMapping='/Account/*')
global with sharing class SampleRest {
  
    @HttpGet
    global static Account doGet() {
        RestRequest req = RestContext.request;
        String acctId = req.requestURI.substring(req.requestURI.lastIndexOf('/') + 1);
        Account result = [SELECT Id, Name FROM Account WHERE Id =: acctId];
        return result;
    }
  
    @HttpPost
    global static String doPost(String name, String descrp) {
        Account a = new Account(Name = name, Description = descrp);        
        insert a;
        return a.Id;
    }

    @HttpDelete
    global static void doDelete() {
        RestRequest req = RestContext.request;
        String memberId = req.requestURI.substring(req.requestURI.lastIndexOf('/') + 1);
        Account memb = [SELECT Id FROM Account WHERE Id = :memberId];
        delete memb;
    }
    
}

Sample Test Class:

@isTest
private class SampleRestTest {

    @testSetup
    static void dataSetup() {
        Account acc = new Account(Name = 'Testing');
        insert acc;
    }

    static testMethod void testGet() {
        Account acc = [ SELECT Id FROM Account LIMIT 1 ];
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();             
        req.requestURI = '/services/apexrest/Account/' + acc.Id;
        req.httpMethod = 'GET';
        RestContext.request = req;
        RestContext.response= res;
        Account acctResp = SampleRest.doGet();
        system.assertEquals(acctResp.Name, 'Testing');
    }
    
    static testMethod void testPost() {
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();             
        req.requestURI = '/services/apexrest/Account/';
        req.httpMethod = 'POST';
        RestContext.request = req;
        RestContext.response= res;
        String acctId = SampleRest.doPost('Test', 'Testing');
        Account acc = [ SELECT Id, Name, Description FROM Account WHERE Id =: acctId ];
        system.assertEquals(acc.Name, 'Test');
        system.assertEquals(acc.Description, 'Testing');
    }
    
    static testMethod void testDelete() {
        Account acc = [ SELECT Id FROM Account LIMIT 1 ];
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();             
        req.requestURI = '/services/apexrest/Account/' + acc.Id;
        req.httpMethod = 'DELETE';
        RestContext.request = req;
        RestContext.response= res;
        SampleRest.doDelete();
        system.assertEquals( [ SELECT COUNT() FROM Account ], 0);
    }
    
}

Output:

Leave a Reply