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
Abhishek Singh 434Abhishek Singh 434 

Facing error "Methods defined as TestMethod do not support Web service callouts" even after using HTTPCalloutMock

I have tried all possible ways to mock the apex callout but still couldn't get over this error - "Methods defined as TestMethod do not support Web service callouts" .. Please Help.

My Main Class - 
 
public class UpdateOFACResponse {
    
    @invocablemethod
    public static void makeCallout(List<Lead> leads)
    {
        if(!System.isFuture() && !System.isBatch())
        {
            saveResponse(leads[0].id);
        }
    }
    
    
    @future(Callout=true)
    public static void saveResponse(Id leadId)
    { 
        String Result;
        Integer Score;
        List<Lead> cName= [Select Company FROM Lead WHERE ID=:leadId limit 1];
        
        String companyName= String.valueOf(cName[0].Company);  
        String compName = EncodingUtil.urlEncode(companyName,'UTF-8').replace('+','%20') ;
        
        System.debug('Encoded compName>>>>'+ compName);
        
        String loginurl='https://search.ofac-api.com/v2?';
        String apikey='52c4b1bd-8bd8-450e-90e6-3ca9bf5bffaf';
        String format='json';
        String Alias ='false';
        String Name= compName;
        String MinScore='95';
        String Source='SDN,DPL';
        String type='Entity';
        
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(
            loginurl+
            'apiKey='+apikey+
            '&format='+format+
            '&includeAlias='+Alias+
            '&name='+Name+
            '&minScore='+MinScore+
            '&source='+Source+
            '&type='+type);
        
        request.setMethod('GET');
        System.debug('request>>'+request);
        HttpResponse response = http.send(request);
        
        System.debug('response>>'+response.getBody());
        
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 200) 
        {   
            Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            System.debug('results>>'+results);
            
            List<object> apiResponse = (List<Object>)results.get('matches');
             System.debug('apiResponse>>'+apiResponse);
            
            if(!apiResponse.isEmpty()){
             Result = (String)((Map<String,Object>)(((List<Object>)results.get('matches')).get(0))).get('name');
                
             Score = (Integer)((Map<String,Object>)(((List<Object>)results.get('matches')).get(0))).get('score'); 
                
            }
            //System.debug('Result-Name'+ Result);
            
            Id devRecordTypeId = Schema.SObjectType.Lead.getRecordTypeInfosByName().get('Partner Onboarding').getRecordTypeId();
            if(devRecordTypeId!=NULL)
            {
                List<Lead> updateList = new  List<Lead>();
                try{ 
                    List<Lead> lstLead =[SELECT Id,OFAC_Response__c,OFAC_Score__c FROM Lead where RecordtypeId=:devRecordTypeId AND ID=:leadId];
                  
                    lstLead[0].OFAC_Response__c= Result;
                    lstLead[0].OFAC_Score__c = Score;
                    updateList.add(lstLead[0]);
                    
                    if(updateList.size()>0)
                    {
                        update updateList;
                    }
                     
                }
                catch(exception e)
                {
                    System.debug('Error occured'+ e.getMessage());
                }
            }
        }   
    }   
}

Test Class- 
 
@isTest(SeeAllData=false)
global class UpdateOFACResponse_Test {
    
    @TestSetup
    static void makeData(){
        RecordType rt = [select id,Name from RecordType where SobjectType='Lead' and Name='Partner Onboarding' Limit 1];
        
        Lead lead = new lead(
            FirstName = 'Test First Name',
            LastName = 'Sample Last Name',
            Phone = '555-555-5555',
            MobilePhone='+17072766457',
            Company = 'ananimforceTest',
            recordTypeId=rt.id
        );
        insert lead;     
    }
    
    @isTest
    static void testCallout() {
        
        List<Lead> lstLead = [SELECT Id, FirstName, LastName,Phone,MobilePhone FROM lead LIMIT 1];
        
        Test.startTest();
        //Set mock callout class.
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        // UpdateOFACResponse.makeCallout(lstLead);
        UpdateOFACResponse.saveResponse(lstLead[0].id);
        Test.StopTest();
        
    }
    
    global class MockHttpResponseGenerator implements HttpCalloutMock {
        // Implement this interface method
        global HTTPResponse respond(HTTPRequest req) {
            String fullJson = ('{error=false, matches=({additionalSanctions=(), addresses=({address1=Calle 50 Y 53 Marbella, address2=Edificio Plaza 2000, address3=Piso 7, city=Panama City, country=Panama, uid=0}), akas=(), citizenship=(), name=GLOBAL TECHNOLOGY IMPORT & EXPORT, S.A. (GTI), passports=(), programs=(SDNTK), score=96, sdnType=Entity, source=SDN, ...}), searchTerm=GLOBAL IMPORT LTD, sourcesUsed=({source=SDN}, {source=DPL})}');
            // Create a fake response
            HttpResponse res = new HttpResponse();
            res.setHeader('Content-Type', 'application/json');
            res.setBody(fullJson);
            res.setStatusCode(200);
            return res;
        }
    } 
    
}
Best Answer chosen by Abhishek Singh 434
{tushar-sharma}{tushar-sharma}
Because these methods will be called on record creation and before you set the mock you are creating the record. So Call the mock class before lead creation.


If this answer helps you, please mark it as accepted.

Regards,
Tushar Sharma
https://newstechnologystuff.com/

All Answers

{tushar-sharma}{tushar-sharma}
Because these methods will be called on record creation and before you set the mock you are creating the record. So Call the mock class before lead creation.


If this answer helps you, please mark it as accepted.

Regards,
Tushar Sharma
https://newstechnologystuff.com/
This was selected as the best answer
David Zhu 🔥David Zhu 🔥
@Abshishek, Your code has no issue in general. But at line 36, the message you built is incorrect.
You have to change line 36 in your test class. 

String fullJson = '{"error":false,"matches":[{"additionalSanctions":[],"addresses":[{"address1":"Calle 50 Y 53 Marbella","address2":"Edificio Plaza 2000","address3":"Piso 7","city":"Panama City","country":"Panama","uid":0}],"akas":[],"citizenship":[],"name":"GLOBAL TECHNOLOGY IMPORT & EXPORT, S.A.","passports":[]}],"searchTerm":"GLOBAL IMPORT LTD","sourcesUsed":[{"source":"SDN"},{"source":"DPL"}]}';            // Create a fake response
           
Tips: you can use this site to make sure your JSON message is correct.  https://jsonformatter.org/


 
Abhishek Singh 434Abhishek Singh 434
Hi All, 
Thanks For replying, I solved this issue myself,  however Tushar was correct... :-) Problem is creating the Test Setup method, actually there was on e process builder which is running as soon as Lead record is created and also it initiate te apex callout, So when I inserting Lead record in Test Setup method it triggers Webservice callout.
To solve this I removed test setup method and insert data inside my test method testCallout() and it works