0

How can I test this for 100% coverage?

@HttpGet
global static List<Box__c> getBox(){
    RestRequest req = RestContext.request;
    String boxId = req.params.get('Id');
    if(boxId == null)
    {
        return [SELECT Id, Title__c
                FROM Box__c
                LIMIT 1000];
    }
    else
    {
        List<Box__c> boxList;
        boxList = [SELECT Id, Title__c 
                   FROM Box__c
                   WHERE Id =: boxId
                   LIMIT 1000];
        return boxList;
    }
}

It can't see else block. My test It works, but only 80%:

@isTest
static void testBox() {
    Id recordId = idd();
    RestRequest request = new RestRequest();
    request.requestUri = System.URL.getSalesforceBaseUrl().toExternalForm() + '/services/apexrest/Box__c/' + recordId;            
    request.httpMethod = 'GET';
    RestContext.request = request;

    List<Box__c> b = OurClass.getBox();

    for(Box__c pneBox : b){
        System.assertEquals(pneBox.Id, recordId);
    }
}

static Id idd() {
    Box__c bb = new Box__c(
        Title__c = 'Title',
    );
    insert bb;
    return bb.Id;
}
  • What's the 20%? You need to describe which lines or sections are not being covered. – David Cheng Oct 5 '18 at 14:43
  • Updated. It can't see else block. – MichaelLev19 Oct 5 '18 at 14:49
  • you never set the RestRequest.params in the testmethod – cropredy Oct 5 '18 at 15:06
  • 1
    Repeating part of what I said in the version of this question that you deleted... Instead of focusing on coverage, I suggest focusing on making sure that you test a variety of situations. Coverage is driven by how much of your code is executed, across all of your unit test methods. By testing a sufficient number of situations (and each situation should be its own test), you'll naturally execute a large portion of your code. An example: 1 test for the situation where the Id parameter is null, and another, separate test method for the situation where the Id parameter is not null. – Derek F Oct 5 '18 at 15:11
  • Ok. I make String boxId = req.params.get('id');, make System.assertEquals(jobAdvertisement.Id, boxId); and it's all the same thing. – MichaelLev19 Oct 5 '18 at 15:14
0

URL parameters are case-sensitive, so your boxId is always null. You need to use

String boxId = req.params.get('id');
  • Ok. I make String boxId = req.params.get('id');, make System.assertEquals(jobAdvertisement.Id, boxId); and it's all the same thing. – MichaelLev19 Oct 5 '18 at 15:25

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.