[SalesForce] Test class for a controller that has logic to query the external object records

We have enabled the Lightning connect and defined an External Data Source for Lightning Connect – Odata 2.0 Adapter and the External Object records are loaded from Informatica. The functionality basically displays all the external object records related to an Account (External object is related to Account – indirect lookup relationship), on the Account detail page as an inline VF page. When the external object records are queried, in the background a REST callout is made. So the Test class needs to use a Test.setMock() method to set a mock response.
Here is the code snippet that I'm using:

static testMethod void PositiveTestCase() {
    // test user - currentUser
    system.runAs(currentUser){

        //Setup Test Data
        //Mock response
        String testResp = 'CUSTOMER_SALES_HISTORY__x:{DisplayUrl=TEST,CUSTOMER_SALES_HISTORY_IID__c=TEST,ExternalId=TEST,SAP_CUSTOMER_NUMBER__c = 0000001003, PRODUCT_LINE__c  = LINEA, PRODUCT_NAME__c =PRD1 PRODUCT_TYPE__c = TYPEA}, CUSTOMER_SALES_HISTORY__x:{DisplayUrl=TEST1,CUSTOMER_SALES_HISTORY_IID__c=TEST1,ExternalId=TEST1,SAP_CUSTOMER_NUMBER__c =1234, PRODUCT_LINE__c  = LINEA, PRODUCT_NAME__c =PRD2 PRODUCT_TYPE__c = TYPEB}';

        //Test class that implements HttpCalloutMock and returns a reusable response
        Test_ReusableMockResponse fakeResponse = new Test_ReusableMockResponse(200,'SUCCESS',testResp, null);

        Test.setMock(HttpCalloutMock.class, fakeResponse);
        Test.startTest();
        //set the standard Controller to the test Account created
        ApexPages.StandardController std = new ApexPages.StandardController(testAccount);
        InlineOrderHistoryViewController controllerInstance = new InlineOrderHistoryViewController(std);
        Test.stopTest();
    }
}

For a straightforward – web service built on REST, this mock response approach should ideally work. Considering the mock response as the real time response received, the unit test case scenario should cover the code.

But in this case, the mock response is not considered as the real time response in the unit test method and all the subsequent lines of code aren't covered.

Also, the Test.setMock() does help in overcoming -' Test methods to not support the WebService Callout' error. So I'm totally convinced that I need to cover this the way we cover the code involving web service callouts.

Please let me know if you have a workaround for this.

Thanks,
Sirisha Kodi

Best Answer

I had the same issue and got around it by adding the following to my custom connection class just before I call the getResponse method:

if (Test.isRunningTest()) { 
  Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
}

HttpResponse response = getResponse(url);