• Rahul Jain 152
  • NEWBIE
  • 0 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 4
    Replies
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';
    }
}

 
I have developed some code for Step 5 in the Superbadge, but appear to stuck as I run the test. I am encountering an error and attempting to determine how to configure my code to pass the test. Are there any steps I am missing? I've covered much of the superbadge, but remain stuck here. 
@isTest
global class WarehouseCalloutServiceMock implements HttpCalloutMock {
    // implement http mock callout
    global HttpResponse respond(HttpRequest request){
        
        System.assertEquals('https://th-superbadge-apex.herokuapp.com/equipment', request.getEndpoint());
        System.assertEquals('GET', request.getMethod());
        
    	// Create a fake response
		HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
		response.setBody('[{"_id":"55d66226726b611100aaf741","replacement":false,"quantity":5,"name":"Generator 1000 kW","maintenanceperiod":365,"lifespan":120,"cost":5000,"sku":"100003"}]');
        response.setStatusCode(200);
        return response;
    }
}
@isTest
private class WarehouseCalloutServiceTest {
  // implement your mock callout test here
	@isTest
    static void WarehouseEquipmentSync(){
        Test.startTest();
        // Set mock callout class 
        Test.setMock(HttpCalloutMock.class, new WarehouseCalloutServiceMock()); 
        // This causes a fake response to be sent from the class that implements HttpCalloutMock. 
        WarehouseCalloutService.runWarehouseEquipmentSync();
        Test.stopTest();        
        System.assertEquals(1, [SELECT count() FROM Product2]);        
        
    }
    
}
public with sharing class WarehouseCalloutService {

    private static final String WAREHOUSE_URL = 'https://th-superbadge-apex.herokuapp.com/equipment';
    
    // complete this method to make the callout (using @future) to the
    // REST endpoint and update equipment on hand.
    @future(callout=true)
    public static void runWarehouseEquipmentSync(){
        Http http = new Http();
		HttpRequest request = new HttpRequest();
		request.setEndpoint(WAREHOUSE_URL);
		request.setMethod('GET');
		HttpResponse response = http.send(request);
		// If the request is successful, parse the JSON response.
		if (response.getStatusCode() == 200) {
    		// Deserialize the JSON string into collections of primitive data types.
    		List<Object> equipments = (List<Object>) JSON.deserializeUntyped(response.getBody());
            List<Product2> products = new List<Product2>();
            for(Object o :  equipments){
                Map<String, Object> mapProduct = (Map<String, Object>)o;
                Product2 product = new Product2();
                product.Name = (String)mapProduct.get('name');
                product.Cost__c = (Integer)mapProduct.get('cost');
                product.Current_Inventory__c = (Integer)mapProduct.get('quantity');
                product.Maintenance_Cycle__c = (Integer)mapProduct.get('maintenanceperiod');
                product.Replacement_Part__c = (Boolean)mapProduct.get('replacement');
                product.Lifespan_Months__c = (Integer)mapProduct.get('lifespan');
                product.Warehouse_SKU__c = (String)mapProduct.get('sku');
                product.ProductCode = (String)mapProduct.get('_id');
                products.add(product);
            }
            if(products.size() > 0){
                System.debug(products);
                upsert products;
            }
		}
    }

}

Please Help!



 
I am receiving this error:

"Line: 1, Column: 5
unexpected token: '<'"

when executing this code:

List<Contact> conList = new List<Contact> {
    new Contact(FirstName='Joe', LastName='Smith', Department='Finance'),
    new Contact(FirstName='Kathy', LastName='Smith', Department='Technology'),
    new Contact(FirstName='Caroline', LastName='Roth', Department='Finance'),
    new Contact();
}

Database.SaveResult[] srList = Database.insert(conList, false);

for (Database.SaveResult sr : srList) {
    if(sr.isSuccess()) {
        System.debug('Successfully inserted contact. Contact ID: ' + sr.getID());
    } else{
        for(Database.Error err : sr.getErrors()) {
            System.debug('The following error has occurred.');
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Contact fields that affected this error: ' + err.getFields());
        }
    }
}

in the execute anonymous window in the developer console (this is a trailhead exercise). Thanks in advance for any help.