-1

This question already has an answer here:

**APEX-CLASS**
public class TriggerFlodataWorkflowController
   {
public string inputIds{get;set;}
public List<String> selectedNames{get;set;}
public List<String> selectedIds{get;set;}
public List<selectOption> options{get;set;}
public String selectedOption{get;set;}
public Map<String, String> optionToTransID{get;set;}
public List<String> listOfStrings {get; set;}
public Map<String, Id> productNameToIdMap{get;set;}
public Map<Id, String> productIdToNameMap{get;set;}
public String selectedProduct{get;set;}
public Map<String, String> objToTransIDMap{get;set;}
Map<String,FloDataTransactionIds__c> transIDSetup{get;set;}
Map<String, String> nameToLabelMap{get;set;}
Map<string, FloDataTransactionIds__c> helpTextMap{get;set;}
Map<String, Boolean> notsObjectMap {get;set;}
public List<CPQMigrationJob__c> existingJobs{get;set;}
public String runId{get;set;}
public String currentJobId{get;set;}
public String tabNumber{get;set;}
public Map<Id, List<CPQMigrationJobDetails__c>> jobToDetailsMap{get;set;}
public string message{get;set;}
public List<string> logDetails{get;set;}
public FloDataTransactionIds__c transactionRecord{get;set;}
public List<Map<String, Object>> summaryMap{get;set;}
public List<string> keys{get;set;}

public TriggerFlodataWorkflowController()
{
    tabNumber = '1';
    transactionRecord = new FloDataTransactionIds__c();
    helpTextMap = new Map<string, FloDataTransactionIds__c>();
    selectedIds = new List<String>();
    productIdToNameMap = new Map<Id, String>();
    selectedNames = new List<String>();
    jobToDetailsMap = new Map<Id, List<CPQMigrationJobDetails__c>>();
    existingJobs = [
        SELECT Id,SubmittedDateTime__c, FloName__c, Status__c,FlodataRunId__c,owner.Name, SubmittedBy__c , EndDateTime__c,
        (SELECT Id,ComponentID__c,ComponentName__c,Status__c FROM CPQMigrationJobDetails__r)
        FROM CPQMigrationJob__c ORDER By SubmittedDateTime__c DESC
    ];
    currentJobId = existingJobs[0].Id; 
    runId = existingJobs[0].FlodataRunId__c;
    for(CPQMigrationJob__c job : existingJobs)
    {
        if(job.getSobjects('CPQMigrationJobDetails__r') != null)
        {
            jobToDetailsMap.put(job.Id, job.getSobjects('CPQMigrationJobDetails__r'));
        }
        else
        {
            jobToDetailsMap.put(job.Id, new List<CPQMigrationJobDetails__c>());
        }
    }
    system.debug('jobToDetailsMap -- > '+jobToDetailsMap);
    objToTransIDMap = new Map<String, String>();
    nameToLabelMap = new Map<String, String>();
    notsObjectMap = new Map<String, Boolean>();
    options = new List<selectOption>();
    transIDSetup = FloDataTransactionIds__c.getAll();
    options.add(new SelectOption('','--None--'));
    selectedOption = '';
    for(FloDataTransactionIds__c data : transIDSetup.values())
    {
        objToTransIDMap.put(data.ObjectAPIName__c, data.TransactionID__c);
        SelectOption option = new SelectOption(data.ObjectAPIName__c,data.Name);
        option.setEscapeItem(false);
        options.add(option);
        notsObjectMap.put(data.ObjectAPIName__c, data.NotAnSObject__c);
        nameToLabelMap.put(data.ObjectAPIName__c, data.Name);
        helpTextMap.put(data.ObjectAPIName__c,data);
    }
    inputIds = '';
    productNameToIdMap = new Map<String, Id>();
    listOfStrings = new List<String>();
}
public void triggerFlowData()
{
    HttpRequest req = new HttpRequest();
    HttpResponse res = new HttpResponse();
    Http http = new Http();
    system.debug('notsObjectMap'+notsObjectMap);
    if(notsObjectMap.get(selectedOption))

    {

        req.setEndpoint('callout:FlodataEndPoint/api/sendMessage?transId='+objToTransIDMap.get(selectedOption));

    }
    else
    {
        req.setEndpoint('callout:FlodataEndPoint/api/sendMessage?transId='+objToTransIDMap.get(selectedOption)+'&RecordId='+inputIds);
    }
    req.setMethod('POST');
    req.setCompressed(true);      
    try {
        res = http.send(req);
        system.debug('result '+res);
        if(res.getStatusCode() == 200)
        {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.CONFIRM, 'Request submitted!'));
            String[] finalSelectedIds = inputIds.split(',');
            inputIds = '';  
            selectedIds = new List<String>();
            Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
            system.debug('response body -- > '+results.get('runId'));
            selectedProduct = '';
            CPQMigrationJob__c job = new CPQMigrationJob__c();
            job.FloName__c = nameToLabelMap.get(selectedOption);
            job.SubmittedDateTime__c = System.Now();
            job.status__c = 'Submitted';
            job.FlodataRunId__c = String.valueOf(results.get('runId'));
            job.External_Id__c = string.valueOf(results.get('runName'));
            insert job;
            existingJobs.add(job);
            system.debug('job id '+job);
            List<Id> detailIds = new List<Id>();
            List<CPQMigrationJobDetails__c> details = new List<CPQMigrationJobDetails__c>();
            if(!notsObjectMap.get(selectedOption)){ 
                system.debug('not sobject');
                for(String selectedId : finalSelectedIds)
                {
                    String idTrimmed = selectedId.remove('\'');
                    CPQMigrationJobDetails__c detail = new CPQMigrationJobDetails__c();
                    detail.Job__c = job.Id;
                    detail.ComponentID__c = selectedId;
                    detail.ComponentName__c = productIdToNameMap.get(idTrimmed);
                    detail.Status__c = 'Submitted';
                    details.add(detail);
                }
                insert details;

                jobToDetailsMap.put(job.Id, details);
            }
            // Modified to create new record for blanket migration i.e., not sobject - 8-5-19
            else
            {
                CPQMigrationJobDetails__c detail = new CPQMigrationJobDetails__c();
                detail.Job__c = job.Id;
                //detail.ComponentID__c = selectedId;
                detail.ComponentName__c = job.FloName__c;
                detail.Status__c = 'Submitted';
                //detail.External_Id__c = detail.name;   
                insert detail;

                system.debug('detail '+detail);
            } 

            //CPQMigrationJobDetails__c
            existingJobs = [
                SELECT Id, SubmittedDateTime__c, Status__c, FloName__c,Owner.Name,SubmittedBy__c,
                FlodataRunId__c, EndDateTime__c 
                FROM CPQMigrationJob__c ORDER By SubmittedDateTime__c DESC
            ];
        }
    } catch(System.CalloutException e) {
        System.debug('Callout error: '+ e);
        System.debug(res.toString());
    }
}


public void fetchStatus()
{
    HttpRequest req = new HttpRequest();
    HttpResponse res = new HttpResponse();
    Http http = new Http();
    req.setEndpoint('callout:FlodataEndPoint/api/getJobStatus?runId='+runId);
    req.setMethod('GET');
    req.setCompressed(true);
    try {
        res = http.send(req);
        if(res.getStatusCode() == 200)
        {
            inputIds = '';
            Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
            system.debug('response body -- > '+results);
            String newStatus = String.valueOf(results.get('jobStatus'));
            string s = string.valueOf(results.get('jobCompletedTime'));
            if(s != null)
                s = s.replace('/','-');

            system.debug('s date '+s);
            //Datetime d = Datetime.valueOf(s);
            Id migrationJobId;
            List<CPQMigrationJobDetails__c> updateMigrationJobDetails = new List<CPQMigrationJobDetails__c>();
            for(CPQMigrationJob__c job : existingJobs)
            {
                if(job.FlodataRunId__c == runId)
                {
                    job.Status__c = newStatus;
                    if(s != null)
                        job.EndDateTime__c  = DateTime.Valueof(s);
                    //system.debug('test date '+jobDetail.EndDateTime__c);

                    // Modified by sridevi to update Migration Job Detail Records - 8-5-19
                    if(jobToDetailsMap.containsKey(job.id) && jobToDetailsMap.get(job.id) != null) {
                        for(CPQMigrationJobDetails__c jobDetail : jobToDetailsMap.get(job.id)) {
                            jobDetail.Status__c = newStatus;
                            if(s != null) {

                                //jobDetail.EndDateTime__c = datetime.parse(string.valueOf(results.get('jobCompletedTime')));

                            }
                            updateMigrationJobDetails.add(jobDetail);
                        }
                        jobToDetailsMap.put(job.id, updateMigrationJobDetails);
                    }
                    // End 

                }
            }
            update existingJobs;
            update updateMigrationJobDetails;

        }
    } catch(System.CalloutException e) {
        System.debug('Callout error: '+ e);
        System.debug(res.toString());
    }
}

public void addProdID()
{
    system.debug('input ids '+inputIds);
    String selectedProdId = productNameToIdMap.get(selectedProduct);
    system.debug('selectedProdId -- > '+selectedProdId);
    system.debug('selected ids '+selectedIds);
    selectedNames.add(selectedProduct);
    if(!inputIds.contains(selectedProdId)){
        if(inputIds == '')
        {
            inputIds = '\''+selectedProdId+'\'';
        }
        else
        {
            inputIds += ','+'\''+selectedProdId+'\'';
        }
        selectedIds.add(selectedProdId);
    }
    system.debug('inputIds -- > '+inputIds);
}

public void refreshCollections()
{
    system.debug('refreshCollections -- > ');
    listOfStrings = new List<String>();
    productNameToIdMap = new Map<String, Id>();
    selectedProduct = '';
    inputIDs = '';
    system.debug('selected op '+selectedOption);
    system.debug('help text map '+helpTextMap);
    if(selectedOption != null && selectedOption != '' && selectedOption != 'NoObj' && selectedOption != 'PreReq')
    {
        String query = 'Select Id, Name from '+selectedOption;
        for(sObject obj : Database.query(query))
        {
            listOfStrings.add(String.valueOf(obj.get('name')));
            productIdToNameMap.put((Id)obj.get('id'), String.valueOf(obj.get('name')));
            productNameToIdMap.put(String.valueOf(obj.get('name')), (Id)obj.get('id'));
        }

    }
    else
    {
        listOfStrings = new List<String>();
        productNameToIdMap = new Map<String, Id>();
    }
    // Below logic is to get the help text for the object
    if(helpTextMap.containsKey(selectedOption)) 
        transactionRecord = helpTextMap.get(SelectedOption);

    system.debug('listOfStrings -- > '+listOfStrings);

}

public void switchTab()
{
    tabNumber = 'Details';
    // Modified by sridevi to update the map when new job is created to display in the vf - 8-5-19
    if(currentJobId != null && !jobToDetailsMap.containsKey(currentJobId)) {
        List<CPQMigrationJobDetails__c> jobDetails = [select id,Status__c,Job__r.FlodataRunId__c,
                                                      ComponentName__c from CPQMigrationJobDetails__c where Job__c =: currentJobId];
        jobToDetailsMap.put(currentJobId, jobDetails);
    }
}
public pageReference back() {
    pageReference pg = new PageReference('/apex/TriggerFlodataWorkflow');
    return pg;
}
// Below method is used to get the migration result
public void getSummaryDetail() {
    summaryMap = new List<Map<String, Object>>();
    if(runId != null && runId != '') {
        // Below query is to get the summary from "Mail Summary" field from Migration Job object.
        CPQMigrationJob__c job = [select id, FlodataRunId__c, Mail_Summary__c from CPQMigrationJob__c where FlodataRunId__c =: runId];
        if(job.Mail_Summary__c != null) {
            Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(job.Mail_Summary__c);
            Object obj = results.get('MailSummary'); 
            List<Object> responseList = (List<Object>)obj;
            summaryMap = new List<Map<String, Object>>();
            for(Object objt : responseList) {
                Map<String, Object> singleMap = (Map<String, Object>)objt; 
                if(singleMap.get('Total') == null)
                    singleMap.put('Total',0);
                if(singleMap.get('Error') == null)
                    singleMap.put('Error',0);
                if(singleMap.get('Success') == null)
                    singleMap.put('Success',0);      
                if(singleMap.get('Object') != null && singleMap.get('Object') != 'Object')
                    summaryMap.add(singleMap);                                        
            }
            keys = new List<string>{'Object','Operation','Success','Error','Total'};
                }
    }
    tabNumber = 'Summary';
}
// Below method is used to get log detail for the migration
public void getLogs() {
    logDetails = null;
    HttpRequest req = new HttpRequest();
    HttpResponse res = new HttpResponse();
    Http http = new Http();
    // callout to get the log detail from flo data
    req.setEndpoint('callout:FlodataEndPoint/api/getLog?runId='+runId);
    req.setMethod('GET');
    req.setCompressed(true);
    string log = null;
    try {
        // sending the http request
        res = http.send(req);
        if(res.getStatusCode() == 200)
        {  
            Map<string,object> resultMap = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
            if(resultMap.get('log') != null)
                log = string.valueOf(resultMap.get('log'));
            if(log != null) 
                logDetails = log.split('\n');
        }
    }catch(System.CalloutException e) {
        System.debug('Callout error: '+ e);
    } 

    tabNumber = 'Logs';

}

}

Testclass:

@isTest
global class TriggerFlodataWorkflowControllerTest implements HttpCalloutMock
{
public string inputIds1{get;set;}
public List<String> selectedNames1{get;set;}
public List<String> selectedIds1{get;set;}
public String selectedOption{get;set;}

public List<selectOption> options1{get;set;}
public Map<String, String> optionToTransID1{get;set;}
public List<String> listOfStrings1 {get; set;}
public Map<String, Id> productNameToIdMap1{get;set;}
public Map<Id, String> productIdToNameMap1{get;set;}
public String selectedProduct1{get;set;}
public Map<String, String> objToTransIDMap1{get;set;}
public Map<String,FloDataTransactionIds__c> transIDSetup1{get;set;}
Map<String, String> nameToLabelMap1{get;set;}
Map<string, FloDataTransactionIds__c> helpTextMap1{get;set;}
Map<String, Boolean> notsObjectMap1 {get;set;}
public List<CPQMigrationJob__c> existingJobs1{get;set;}
public String runId1{get;set;}
public String currentJobId1{get;set;}
public String tabNumber1{get;set;}
public Map<Id, List<CPQMigrationJobDetails__c>> jobToDetailsMap1{get;set;}
public string message1{get;set;}
public List<string> logDetails1{get;set;}
public FloDataTransactionIds__c transactionRecord1{get;set;}
public List<Map<String, Object>> summaryMap1{get;set;}
public List<string> keys1{get;set;}

static void setUpData(){

    CPQMigrationJob__c CPQobj = new CPQMigrationJob__c();
    CPQobj.SubmittedDateTime__c = DateTime.parse('05/22/2012 11:46 AM');
    CPQobj.FloName__c = 'Blanket Migration';
    CPQobj.Status__c = 'Completed';
    CPQobj.FlodataRunId__c = '9428';
    insert CPQobj;

    CPQMigrationJobDetails__c CPQMigobj = new CPQMigrationJobDetails__c();
    CPQMigobj.ComponentID__c = '01tK0000006ceK5IAI';
    CPQMigobj.Job__c = CPQobj.Id ;
    CPQMigobj.ComponentName__c = 'Blanket';
    CPQMigobj.Status__c = 'Blanket';

    insert CPQMigobj;

    FloDataTransactionIds__c FloObj =new FloDataTransactionIds__c ();
    FloObj.TransactionID__c='924';
    FloObj.ObjectAPIName__c ='Apttus_Config2__ProductAttributeRule__c';
    FloObj.Name='Attribute Rule';
    FloObj.NotAnSObject__c=True;
    insert FloObj;
    string inputIds = ''; 

    Map<String, Boolean> notsObjectMap = new Map<String, Boolean>();
    notsObjectMap.put( FloObj.ObjectAPIName__c, FloObj.NotAnSObject__c);



}  


static testmethod void test1(){


    setUpData();
    Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
    Test.startTest();
    TriggerFlodataWorkflowController controllerObj = new TriggerFlodataWorkflowController();
    String selectedOption  = 'Apttus_Config2__ProductAttributeRule__c' ;
    controllerObj.triggerFlowData();
    Test.stopTest();

}

global HTTPResponse respond(HTTPRequest request) {
    HttpResponse response = new HttpResponse();
    response.setHeader('Content-Type', 'application/xml');
    response.setBody('{"animal": {"id":1, "name":"Tiger"}}');
    response.setStatusCode(200);
    return response;
}

@isTest 
static void testPostCallout() {
    Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
    test.startTest();

    TriggerFlodataWorkflowController controllerObj = new TriggerFlodataWorkflowController();
    StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
    mock.setStaticResource('mockResponse');
    mock.setStatusCode(200);
    mock.setHeader('Content-Type', 'application/json');
    controllerObj.fetchStatus();

    test.stoptest();
}

static testmethod void test2(){
    setUpData();
    Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
    Test.startTest();
    TriggerFlodataWorkflowController controllerObj = new TriggerFlodataWorkflowController();
    controllerObj.fetchStatus();
    Test.stopTest(); 
}    

static testmethod void test3(){
    setUpData();
    Test.startTest();
    TriggerFlodataWorkflowController controllerObj = new TriggerFlodataWorkflowController();
    controllerObj.addProdID();

    Test.stopTest(); 
} 
static testmethod void test4(){
    setUpData();
    Test.startTest();
    TriggerFlodataWorkflowController controllerObj = new TriggerFlodataWorkflowController();

    Test.stopTest(); 
} 
static testmethod void test5(){
    setUpData();
    Test.startTest();
    TriggerFlodataWorkflowController controllerObj = new TriggerFlodataWorkflowController();
    controllerObj.switchTab();
    Test.stopTest(); 
} 

static testmethod void urltest() {
    setUpData();
    Test.startTest();
    TriggerFlodataWorkflowController controllerobj = new TriggerFlodataWorkflowController();
    controllerObj.back();
    Test.stopTest(); 
    pageReference pg = new PageReference('/apex/TriggerFlodataWorkflow');
    Test.setCurrentPage(pg);
}
static testmethod void test6(){
    setUpData();
    Test.startTest();
    TriggerFlodataWorkflowController controllerObj = new TriggerFlodataWorkflowController();
    controllerObj.getSummaryDetail();
    Test.stopTest(); 
} 
static testmethod void test7(){
    setUpData();
    Test.startTest();
    Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
    TriggerFlodataWorkflowController controllerObj = new TriggerFlodataWorkflowController();
    controllerObj.getLogs();
    Test.stopTest(); 
} 
static testmethod void test8(){
    setUpData();
    Test.startTest();
    TriggerFlodataWorkflowController controllerObj = new TriggerFlodataWorkflowController();
    controllerObj.refreshCollections();
    Test.stopTest(); 
}

}

MockTest @isTest

global class MockHttpResponseGenerator implements HttpCalloutMock {

global HTTPResponse respond(HTTPRequest req) {

    // System.assertEquals('allout:FlodataEndPoint/api/getJobStatus? 
    [![enter image description here][1]][1]runId=9428', req.getEndpoint());
    //   System.assertEquals('GET', req.getMethod());
    HttpResponse res = new HttpResponse();
    res.setHeader('Content-Type', 'application/xml');


    return res;
}}

enter image description here enter image description here enter image description here

marked as duplicate by Sebastian Kessel, Jayant Das, Derek F, glls, Vijay Ganji Jun 3 at 6:11

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

Your Mock needs to actually synthesize and return a viable response that resembles what the real web service would return, in order to cause your code to execute the same logical path. Right now, your code probably either returns or throws an exception, because what it gets back from the callout is just empty.

You'll likely need to write several Mock classes to test various code paths, or use a MultiStaticResourceMock to return the content of a different Static Resource based on the endpoint that's being called.

Right now, your Mock doesn't do anything useful. It claims to be returning XML:

res.setHeader('Content-Type', 'application/xml');

while your application expects JSON, but then returns no data at all.

Not the answer you're looking for? Browse other questions tagged or ask your own question.