0

I have this simple little @HttpGet method.

    @HttpGet
    global static List<Case> getCases() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        List<case> result = [SELECT Id, Type, caseNumber, Subject, Status 
                             FROM CASE 
                             WHERE AccountID = :accountId 
                             AND isClosed = false
                             ORDER BY LastModifiedDate DESC 
                             LIMIT 3];
        return result;
    }

which works fine but I don't know how to write a test class for it. I've successfully written test classes for the rest of my code but I can't find an example or documentation that covers this example.

Thank you in advance.

0

1 Answer 1

2

A unit test for this is nothing special. You simply set the static context variables, and call the method as you would any other:

// Create data
Account accountRecord = new Account(Name='Test');
insert accountRecord;
Case caseRecord = new Case(AccountId=accountRecord.Id, Subject='Test', Priority='Normal', Status='Open');
insert caseRecord;

// Set up context variables
RestContext.request = new RestRequest();
RestContext.response = new RestResponse();
RestContext.request.requestURI = 'something/somethingelse/'+accountRecord.Id;

// Test the method
Test.startTest();
Case[] results = MyCaseClass.getCases();

// Assert the results
System.assertEquals(caseRecord.Id, results[0].Id);

There's nothing special going on here if you've written a unit test before, just the added wrinkle of setting some static variables.


Side note.

There's a better method for getting the ID out of the URI, namely substringAfterLast:

String accountId = req.requestURI.substringAfterLast('/');
1
  • Thank you for your help @sfdcfox Commented Nov 8, 2021 at 7:43

Not the answer you're looking for? Browse other questions tagged .