function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
saiisaii 

Testcase help

Hi

I have small doubt .I am calling the rest Request in my class.If i get the status code=200 then that  If condition will execute else an error message will be display  It is working fine,,,,,,

How to cover that part in testcase in class......please help  me


//construct an HTTP request
HttpRequest req = new HttpRequest();

req.setEndpoint('sample endpoint');
req.setMethod('POST');

//send the request
Http http = new Http();
HttpResponse res = http.send(req);

//check the response
if (res.getStatusCode() == 200)
{
insert contact;
}
else
{
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR, 'Request Fail');
ApexPages.addMessage(myMsg);
}

 

thanks in advances

 

 

logontokartiklogontokartik

You have 2 choices here. 

 

1. You can change your code to create a Test Response if a test is running, something like 

 

public HttpResponse testResponse; // define this variable to use in test class

 

// while sending request check if test is running.

HttpResponse res;

 

if(!Test.isRunningTest())

res = Http.send(req);

else

res = testResponse;

 

Now you can build your testResponse in whatever way you need. You can use res.setStatusCode() method to set code to 400, 500 or anything and also you can setBody(). 

 

 

2. The second approach is to Implement HttpCalloutMock interface and creating a HttpResponse Mock. Please see the documentation below

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_restful_http_testing_httpcalloutmock.htm

 

saiisaii

Hi Karthik can u please explain the First method or can u send one exampleu have done.I  need to increase my testcase percentage please 

thanks in advances