Sunday 11 January 2015

Testing HTTP Callouts by Implementing the HttpCalloutMock Interface

global class MockHttpResponseGenerator implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
        System.assertEquals('http://api.salesforce.com/foo/bar', req.getEndpoint());
        System.assertEquals('GET', req.getMethod());
        
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"foo":"bar"}');
        res.setStatusCode(200);
        return res;
    }
}
public class CalloutClass {
    public static HttpResponse getInfoFromExternalService() {
        HttpRequest req = new HttpRequest();
        req.setEndpoint('http://api.salesforce.com/foo/bar');
        req.setMethod('GET');
        Http h = new Http();
        HttpResponse res = h.send(req);
        return res;
    }
}
@isTest
                        
private class CalloutClassTest {
     @isTest static void testCallout() {
        // Set mock callout class 
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        
        // Call method to test.
        // This causes a fake response to be sent
        // from the class that implements HttpCalloutMock. 
        HttpResponse res = CalloutClass.getInfoFromExternalService();
        
        // Verify response received contains fake values
        String contentType = res.getHeader('Content-Type');
        System.assert(contentType == 'application/json');
        String actualValue = res.getBody();
        String expectedValue = '{"foo":"bar"}';
        System.assertEquals(actualValue, expectedValue);
        System.assertEquals(200, res.getStatusCode());
    }
}

Saturday 10 January 2015

Testing SOSL


Use       Test.setFixedSearchResults


Class

public class MySearchClass{
    public Static void doSearch(String search){
        List<List<Sobject>> searchResult;
        searchResult=[FIND :search IN ALL FIELDS RETURNING Account];
        if(searchResult!=null){
            System.debug('in if'+searchResult);
            searchResult=[FIND :search IN ALL FIELDS RETURNING Account];
        }
        else{
            System.debug('in else'+searchResult);
            searchResult=[FIND :search IN ALL FIELDS RETURNING Account];
        }
    }
}

Test Class

@isTest
public class TestMySearchClass{
    private static testMethod void testMeth(){
        Account acc = new Account(Name='testBaljeet');
        insert acc;
        Test.setFixedSearchResults(new List<Id>{acc.id});
        MySearchClass.doSearch('test');
    }
}

Load TestData Using Static Resource CSV file in Test Class


@isTest
static testMethod void static_testResource(){
          List<sobject> cand=Test.loadData(Account.sObjectType,'testAccount');
}