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
Rahul Jain 152Rahul Jain 152 

Test Class for REST Integration Apex Class

I need help writing a test class for the below apex class using a mock test :
 
Apex Class First

public with sharing class B2B_wordlineCreateHostedCheckout {
    
    @AuraEnabled
    public static String createHostedCheckout(String shopName, String issuerId) {
        try {
            String shopNameTemp = shopName;
            String newShopName = shopName.substring(1);
            Http httpCall = new Http();
            HttpRequest httpRequest = new HttpRequest();
            Map<String, B2B_Wordline_Config__mdt> shopDetailsMap = B2B_Wordline_Config__mdt.getAll();
            system.debug('shopDetailsMap11'+shopDetailsMap);
            String apiKey = shopDetailsMap.get(newShopName).apiKey__c;
            String apiSecret = shopDetailsMap.get(newShopName).apiSecret__c;
            String pspId = shopDetailsMap.get(newShopName).pspId__c;
            String hostName = shopDetailsMap.get(newShopName).hostName__c;
            String webStoreName = shopDetailsMap.get(newShopName).webStoreName__c;
            String requestMethod = 'POST';
            String contentType = 'application/json';
            String uriResource = '/hostedcheckouts';
            String endpointURL = '/v2/' + pspId + uriResource;
            String responseString = '';
            String UserId = UserInfo.getUserId();
            System.debug('Community User Id: ' + UserId);
            System.debug('webStoreName+++28'+webStoreName);
            
            // Retrieve the latest cart for the user
            WebCart cart = [SELECT Id, GrandTotalAmount, CurrencyIsoCode FROM WebCart 
                            WHERE Owner.id = :UserId
                            AND Status = 'Checkout'
                            AND WebStore.Name = :webStoreName 
                            ORDER BY LastModifiedDate DESC LIMIT 1];
            System.debug('cart+++28'+cart);
            if (cart == null) {
                throw new AuraHandledException('No cart found for the user.');
            }
            String baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
            Decimal grandTotalAmount = cart.GrandTotalAmount;
            String currencyIsoCode = cart.CurrencyIsoCode;
            String uriEndPoint = '/checkout';
            String checkoutURL = baseUrl + shopNameTemp + uriEndPoint ;
            System.debug('checkoutURL+++41'+checkoutURL);
            String jsonText = '{"order":{"amountOfMoney":{"amount":' + grandTotalAmount + ',"currencyCode":"' + currencyIsoCode + '"}},';
            jsonText += '"hostedCheckoutSpecificInput":{"returnUrl":"' + checkoutURL + '"}';
            if (issuerId != null) {
                jsonText += ',"redirectPaymentMethodSpecificInput":{"paymentProductId":"809","paymentProduct809SpecificInput":{"issuerId":"' + issuerId + '"}}';
            }
            jsonText += '}';
            System.debug('jsonText+++41'+jsonText);
            Map<String, Object> jsonData = (Map<String, Object>) JSON.deserializeUntyped(jsonText);
            String requestBodyJson = JSON.serialize(jsonData);
            System.debug('requestBodyJson+++41'+requestBodyJson);
            httpRequest = B2B_worldlineUtility.makeHttpRequest(endpointURL, requestMethod, contentType, apiKey, apiSecret, requestBodyJson, hostname);
            System.debug('httpRequest+++41'+httpRequest);
            HttpResponse httpResponse = httpCall.send(httpRequest);
            System.debug('httpResponse+++41'+httpResponse);
            return httpResponse.getBody();
        } catch (Exception ex) {
            throw new AuraHandledException('An error occurred: ' + ex.getMessage());
        }
    }

    @AuraEnabled
    public static string getProductDirectory(String shopName) {
        try {
            String currencyISOCode ;
            String userId = UserInfo.getUserId();
            User currentUser = [SELECT Id, CurrencyIsoCode FROM User WHERE Id = :userId LIMIT 1];
            
            if (currentUser != null) {
                currencyISOCode = currentUser.CurrencyIsoCode;
                System.debug('currencyISOCode: ' + currencyISOCode);
            } else {
                throw new AuraHandledException('Currency ISO Code Is Not available');
            }
            
            String newShopName = shopName.substring(1);
            List<String> strings = newShopName.split(';');
            for (String eachString : strings) {
                List<String> nameSplits = eachString.split('/');
                newShopName = nameSplits.get(0).removeStart(' ');
            }
            Http httpCall = new Http();
            HttpRequest httpRequest = new HttpRequest();
            Map<String, B2B_Wordline_Config__mdt> shopDetailsMap = B2B_Wordline_Config__mdt.getAll();
            B2B_Wordline_Config__mdt shopConfig = shopDetailsMap.get(newShopName);
            
            if (shopConfig == null) {
                throw new AuraHandledException('Shop configuration not found for shopName: ' + newShopName);
            }
            
            String apiKey = shopConfig.apiKey__c;
            String apiSecret = shopConfig.apiSecret__c;
            String pspId = shopConfig.pspId__c;
            String hostName = shopConfig.hostName__c;
            String webStoreName = shopConfig.webStoreName__c;
            String countryCode = shopConfig.Country_Code__c;
            String requestMethod = 'GET';
            String contentType = 'application/json';
            String uriResource = '/products/809/directory?countryCode=' + countryCode + '&currencyCode=' + currencyISOCode;
            String endpointURL = '/v2/' + pspId + uriResource;
            String responseString = '';
            httpRequest = B2B_worldlineUtility.makeHttpRequest(endpointURL, requestMethod, contentType, apiKey, apiSecret, null, hostname);
            HttpResponse httpResponse = httpCall.send(httpRequest);
            System.debug('httpResponse.getBody(): ' + httpResponse.getBody());
            return String.valueOf(httpResponse.getBody());
        } catch (Exception ex) {
            throw new AuraHandledException('An error occurred: ' + ex.getMessage());
        }
    }

    @AuraEnabled
    public static String checkForHostedCheckout(String shopName,String hostedCheckoutId) {
        // https://payment.preprod.direct.worldline-solutions.com/v2/{merchantId}/hostedcheckouts/{hostedCheckoutId}
        system.debug('hostedCheckoutId: ' +hostedCheckoutId);
        String newShopName = shopName.substring(1);
        Http httpCall = new Http();
        HttpRequest httpRequest = new HttpRequest();
        Map<String, B2B_Wordline_Config__mdt> shopDetailsMap = B2B_Wordline_Config__mdt.getAll();
        String apiKey = shopDetailsMap.get(newShopName).apiKey__c;
        String apiSecret = shopDetailsMap.get(newShopName).apiSecret__c;
        String pspId = shopDetailsMap.get(newShopName).pspId__c;
        String hostName = shopDetailsMap.get(newShopName).hostName__c;
        String webStoreName = shopDetailsMap.get(newShopName).webStoreName__c;
        String requestMethod = 'GET';
        String contentType = 'application/json';
        String uriResource = '/hostedcheckouts/' + hostedCheckoutId;
        String endpointURL = '/v2/' + pspId + uriResource;
        String responseString = '';
        httpRequest = B2B_worldlineUtility.makeHttpRequest(endpointURL, requestMethod, contentType, apiKey, apiSecret, null, hostname);
        HttpResponse httpResponse = httpCall.send(httpRequest);
        return httpResponse.getBody();
    }    
}

Apex Class Second 

public class B2B_worldlineUtility {
    public static httpRequest makeHttpRequest(String endpointUrl, String requestMethod, String contentType, String apiKey, String apiSecret, String requestBody, String hostname) {
        HttpRequest httpRequest = new HttpRequest();
        httpRequest.setEndpoint('https://' + hostname + endpointURL);
        httpRequest.setMethod(requestMethod);
        if (requestBody != null) {
            httpRequest.setBody(requestBody);
        }
        httpRequest.setHeader('Content-Type', contentType);
        httpRequest.setHeader('Authorization', 'GCS v1HMAC:' + apiKey + ':' + generateSignatureForGET(requestMethod, contentType, endpointUrl, apiSecret));
        httpRequest.setHeader('Host', hostname);
        httpRequest.setHeader('Date', getFormattedCurrentTime());
        httpRequest.setHeader('Accept-Encoding', 'gzip, deflate, br');
        httpRequest.setHeader('Connection', 'keep-alive');
        httpRequest.setHeader('Accept', 'application/json');
        return httpRequest;
    }

    public static String generateSignatureForGET(String requestMethod, String contentType, String endpointUrl, String apiSecret) {
        if (requestMethod == 'GET' || requestMethod == 'DELETE') {
            contentType = '';
        }
        String stringToHash = requestMethod + '\n' + contentType + '\n' + getFormattedCurrentTime() + '\n' + endpointUrl + '\n';
        Blob hmacSHA256Blob = Crypto.generateMac('HmacSHA256', Blob.valueOf(stringToHash), Blob.valueOf(apiSecret));
        return EncodingUtil.base64Encode(hmacSHA256Blob);
    }

    public static String getFormattedCurrentTime() {
        return Datetime.now().format('EEE, dd MMM yyyy HH:mm:ss') + ' GMT';
    }
}

 
frinksa lilinasfrinksa lilinas
Mock Test Data: Use @isTest annotation to create test data, ensuring this data doesn't interfere with your org's actual data. Test Methods: Create individual test methods for each of your @AuraEnabled methods in the main class. Test HTTP Callouts: Implement the HttpCalloutMock interface to simulate HTTP callouts and provide mock responses. Execute & Assert: Make calls to your main methods from the test methods and use System.assert() to validate the behavior.    https://www.mycvshr.website/
VinayVinay (Salesforce Developers) 
Hi Rahul,

It would be not possible to write test class for above class, however you can check below example reference for rest api web service reference.

https://jayakrishnasfdc.wordpress.com/2021/01/02/apex-test-class-examples-for-web-services/

Thanks,