[SalesForce] HttpRequest and HttpResponse is not covering in test class

I wrote a Testclass(Mock response) by implementing HttpCalloutMock interface to cover HttpRequest in class, I given some fake values to it also. But while calling the class, its not covering in regular test class.

Following is the class to cover http request and response:

Http h = new Http();
HttpRequest req1 = new HttpRequest();
req1.setMethod('POST');
req1.setHeader('Content-Type', 'application/json');
req1.setHeader('Authorization', authorizationHeader);
req1.setbody(reqbody);
req1.setTimeout(120000); 
req1.setEndpoint(endpoint);

HttpResponse res1 = new HTTPResponse();
res1 = h.send(req1);

But, The above class will return string. For the above class i wrote the following mock response test class:

@isTest
global class MockGenerator implements HttpCalloutMock {

    global HTTPResponse respond(HTTPRequest req) {

        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setHeader('Authorization', 'Basic YXBmFtaWx5');
        res.setBody('{"Username":"testuser@test.com", "owner":"testowner@test.com", "uniqueid":"123456789", "email":"testemail@test.com"}');
        res.setStatusCode(200);
        return res;
    }
}

I called the mock response in main test class even, but its not covering. I tried a lot to get cover and always getting fail. DO i am missing any thing. Please guide in this.

Test.setMock(HttpCalloutMock.class, new MockGenerator());
String response = MyRewardAPI.Authenticateuser();

Above one is calling mock test in main test.
Thank you

Best Answer

@isTest classes are not supposed to be in the code coverage list, and should not count towards the code coverage rules (75% covered). Sometimes, however, things get messed up in the database, and you need to manually delete the erroneous coverage records.

To do this:

  • Go to the Developer Console
  • Go to the Query tab
  • Enter the Query SELECT Id, NumLinesCovered FROM ApexCodeCoverageAggregate.
  • Click on the "Use Tooling API" checkbox
  • Select all rows
  • Click Delete to delete the rows
  • Click on Test | Clear Test Coverage.
  • Run your tests again.

Again, your MockGenerator class should not have coverage, and should not count against the coverage requirements. If they are, you need to force the system to exclude them by deleting the relevant records.

Related Topic