+ Start a Discussion
Patrick Mayer 4Patrick Mayer 4 

Difficult test class http requests

I am having an extremely difficult time coming up with a test class for this. 

I am using a multimock for mock data, but I cannot figure out how to set cookies for that.

Http httpProtocol1 = new Http();
		Http httpProtocol2 = new Http();
		// Create HTTP request to send.
		HttpRequest request1 = new HttpRequest();
		HttpRequest request2 = new HttpRequest();
		// Set the endpoint URL.
		String endpoint1 = 'https://web.com/Login.json?user=user%40web.com&pass=secr';
		String endpoint2 = 'https://web.com/info.json';
		// Set the HTTP verbs
		// Send the HTTP requests and get the responses
		HttpResponse response1 = httpProtocol1.send(request1);
		String cookie = response1.getHeader('Set-Cookie');
		request2.setHeader('cookie', cookie);
		HttpResponse response2 = httpProtocol2.send(request2);
		String jsonStr = response2.getBody();

Not sure what multimock is, but with the standard httpCalloutMock stuff you'll want to do something like this: 
  1. Create a class something like this
public class RestClientHTTPMocks implements HttpCalloutMock {

	Protected Integer             code;
	Protected String              status;
	Protected String              bodyAsString;
	Protected Blob                bodyAsBlob;
	Protected Map<String, String> responseHeaders;

	* Constructors.

	public RestClientHTTPMocks(Integer code, String status, String body, Map<String, String> responseHeaders) {
		this.code = code;
		this.status = status;
		this.bodyAsString = body;
		this.bodyAsBlob = null;
		this.responseHeaders = responseHeaders;

	 * This is the interface method need to implement.

	public HTTPResponse respond(HTTPRequest req) {		
		// craft the return response.
		HttpResponse res = new HttpResponse();
		if (this.responseHeaders != null) {
		 	for (String key : this.responseHeaders.keySet()) {
		 		res.setHeader(key, this.responseHeaders.get(key));
		return res;


Then in your test class you set the mock up like this: 
Test.setMock(HttpCalloutMock.class, new RestClientHTTPMocks(
    200, // the response code you want returned by your mock
    'OK', // the status string you want returned by your mock
    'Body as a String', // whatever you want your mock to return as the body of the page
    blobObj, // if you want your page returned as a blob or you're returning an image
    Headers // Map <header-name, header-value> of the headers you want set. 

// Specifically, you'll want to use the headers bit like this
Map<String, String> headers = new Map<String,String>('cookie', 'your cookie value here');

//Then setup your mock thusly:
Test.setMock(HttpCalloutMock.class, new RestClientHTTPMocks(200, 'OK', 'awesomesauce', null, headers);