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;
}
7
  • What's the 20%? You need to describe which lines or sections are not being covered. Oct 5, 2018 at 14:43
  • Updated. It can't see else block. Oct 5, 2018 at 14:49
  • you never set the RestRequest.params in the testmethod
    – cropredy
    Oct 5, 2018 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, 2018 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. Oct 5, 2018 at 15:14

1 Answer 1

0

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

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

You must log in to answer this question.

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