0

I have a webservivce for which i wrote a unittest but there is no code coverage, what am I missing

Webservice

@RestResource(urlMapping='/DynamicApi/*')
global with sharing class DynamicApi{ 
    public static List<List<sObject>> sobjects = new  List<List<sObject>>();  
    @HttpPost
    global static void DynamicApiPost()
    {
        RestRequest req = RestContext.request;
        RestResponse res = Restcontext.response;
        String jsonPayLoad = req.requestBody.toString(); 
        Object source = JSON.deserializeUntyped(jsonPayLoad);
        traverseJson(source);
        for(List<sObject> insSObject : sobjects){
            insert insSObject;
        }
        res.statuscode = 200;
        res.responseBody = Blob.valueOf(string.valueOf(sobjects +'DateTime: ' + system.Datetime.now()));
    }
..
}

Unittest

@isTest
public class DynamicApiTest{
    public static testmethod void  DynamicApiRestPost() {
        string jsonPayLoad ='{"Accts": [{"jname": "Alice","P": "+00 0600000000","Showstopper": true,"Empl": "1-10","Opp": [{"Oname": "Opp1","CLdate": "02-02-2021",' +
            '"Aname":"0019Y00001HGZDxXYZ"},{"Oname": "Opp2","CLdate": "03-03-2021","Aname":"0019Y00001HGZDxXYZ"}]},{"jname": "Ben","P": "+00 0611111111","Showstopper": true,' +
            '"Empl": "11-50"}],"Cont": [{"lname": "Anton","Ph": "+00 0600000000"},{"lname": "Bjorn","Ph": "+00 0611111111"}]}';
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();
        req.requestUri = '/services/apexrest/DynamicApi';
        req.httpMethod = 'POST';
        req.addHeader('Content-Type', 'application/json');
        req.addHeader('Accept', 'application/json');
        
        req.requestBody = Blob.valueOf(jsonPayLoad);
        RestContext.request = req;
        RestContext.response= res;

        System.Test.startTest();
        List<Account> thisAccount = [SELECT Id,Name FROM Account];       
        System.Test.stopTest();
        System.assert(thisAccount != null);
    }
}
0

1 Answer 1

3

As with any other method you want to cover, you have to actually call it.

@IsTest static void myTest()
{
    // setup as is
    
    Test.startTest();
        DynamicApi.DynamicApiPost();
    Test.stopTest();
    
    // query results
    // assert behavior
}
0

This site is temporarily in read-only mode and not accepting new answers.

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