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
Mrunali GaonkarMrunali Gaonkar 

hi, i want to write a test class for controller in which there is a webservice callout.. using webservicemock am getting response as null..confused.how to write test code

apex page


<apex:page standardController="Project_Name__c" extensions="GetAndMapWingPlantCodeController"> <apex:pageMessages /> <apex:form > <!-- <apex:pageblock rendered="{!blnResponseForPlantCode}"> --> <apex:pageblock rendered="{!blnNoAssociatedWings}"> <apex:pageBlockSection title="Map Wings to Plant code" columns="2"> <apex:repeat value="{!listWingPlantCode}" var="wing"> <apex:pageBlockSectionItem > <apex:outputLabel value="Cluster {!wing.objWing.Cluster__r.Name} Wing {!wing.objWing.Name}"/> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:selectList value="{!wing.strPlantCode}" multiselect="false" size="1" required="true"> <apex:selectOptions value="{!plantCode}" /> </apex:selectList> </apex:pageBlockSectionItem> </apex:repeat> </apex:pageBlockSection> <apex:pageBlockButtons > <apex:commandButton action="{!saveMapping}" value="Save" onComplete="window.self.close();"/> <apex:commandButton action="{!cancel}" value="Cancel" onComplete="window.close();"/> </apex:pageBlockButtons> </apex:pageblock> </apex:form> </apex:page>


apex class

public class GetAndMapWingPlantCodeController {
    
    // Variables
    String projectId;
    public List<Wing__c> listWing = new List<Wing__c>();
    public List<Project_Name__c> listProject = new List<Project_Name__c>();
    //public boolean blnIncorrectPlantMapping;
    private ApexPages.StandardController stdController;
    String returnMsg;
    
    // Properties
    public List<WingPlantCodeMapping> listWingPlantCode {get; set;}
    public Map<String, List<Wing__c>> mapPlantCodeWing {get; set;}
    public boolean blnResponseForPlantCode {get; set;}
    public boolean blnNoAssociatedWings {get; set;}
    public boolean blnIncorrectPlantMapping {get; set;}
    public WingPlantCodeMapping objWingPlantCode {get; set;}
    public List<String> listPlantCode {get; set;}
   
    //public List<String> listPlantCode {get; set;}
    
    // final variables
    private static final String SAP_AUTH_USERNAME = System.Label.SapAuthUsername;
    private static final String SAP_AUTH_PASSWORD = System.Label.SapAuthPassword;
    
    public GetAndMapWingPlantCodeController(){}
    
    //Constructor
    public GetAndMapWingPlantCodeController(ApexPages.standardController objStdController){
        
        // Initialization
        blnResponseForPlantCode = true;
        blnIncorrectPlantMapping = false;
        blnNoAssociatedWings = true;
        listWingPlantCode = new List<WingPlantCodeMapping>();
        objWingPlantCode = new WingPlantCodeMapping();
        listPlantCode = new List<String>();
        
        stdController = objStdController;
        projectId= objStdController.getId();
        
        listProject = [select id,
                              Name, 
                              Sales_Organization__c 
                       from Project_Name__c 
                       where id = :projectId];
        
        if(!listProject.isEmpty()){
            listWing = [select id, 
                               Name, 
                               Project__c, 
                               Cluster__r.Name, 
                               SAP_Plant_Code__c 
                        from Wing__c 
                        where Project__c = :listProject[0].Name];
        
            // If wings are created for this project then
            // consume the SAP webservice to get the plant code for each wing
            if(!listWing.isEmpty()){
                InitializeListWingPlantCode(listWing);
                // Calling the SAP WSDL method to get the plant code
                try{
                    returnMsg = callInventoryService(projectId);
                    if(!String.isBlank(returnMsg)){
                        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, returnMsg));
                        blnResponseForPlantCode = false;
                    }
                    else
                        blnResponseForPlantCode = true;
                }
                catch(Exception e){
                    blnResponseForPlantCode = false;
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Exception : ' + e));
                }
            }// end of listWing.isEmpty()
            else{
                blnNoAssociatedWings = false;
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'There are no wings associated with this Project.'));
            }
        } // end of if(listProject.isEmpty)
    } 
    
    // Method to create the select list of the Plant codes.
    public List<SelectOption> getPlantCode(){
   
        List<SelectOption> plantCodeOptions = new List<SelectOption>();
        plantCodeOptions.add(new SelectOption('','-None-'));
        system.debug('listPlantCode'+listPlantCode);
        //Mrunali Gaonkar
        if(!listPlantCode.isEmpty()){
          for(String strItem : listPlantCode){
              plantCodeOptions.add(new SelectOption(strItem,strItem));
          }
          return plantCodeOptions;
        }else{
            return null;
        }
    }
    
    // Method to create the list of Wing and corrosponding Plant Code
    public void InitializeListWingPlantCode(List<Wing__c> pListWing){
        
        for(Wing__c wing : pListWing){
            objWingPlantCode = new WingPlantCodeMapping();
            objWingPlantCode.objWing = wing;
            objWingPlantCode.strPlantCode = '';
            listWingPlantCode.add(objWingPlantCode);
        }        
    }
    
    // Method to save the Palnt corrosponding to the wing
    public void saveMapping(){
        
        String strPlantName;
        List<Wing__c> listWingForSamePlantCode = new List<Wing__c>();
        List<Wing__c> listWingToUpdate = new List<Wing__c>();
        mapPlantCodeWing = new Map<String, List<Wing__c>>();
        
        if(!listWingPlantCode.isEmpty()){ 
            
            for(WingPlantCodeMapping objWingPlant : listWingPlantCode){
                strPlantName = objWingPlant.strPlantCode;
                listWingForSamePlantCode = new List<Wing__c>();
                
                for(WingPlantCodeMapping objWingPlant1 : listWingPlantCode){
                    if(strPlantName.equals(objWingPlant1.strPlantCode)){
                        listWingForSamePlantCode.add(objWingPlant1.objWing);
                        objWingPlant1.objWing.SAP_Plant_Code__c = objWingPlant1.strPlantCode;
                        listWingToUpdate.add(objWingPlant1.objWing);
                    }
                }
                if(!listWingForSamePlantCode.isEmpty())
                    mapPlantCodeWing.put(strPlantName, listWingForSamePlantCode);
            }
        
            // Checking whether if two wings are associated with one plant code
            //MRUNALI GAONKAR 22/04/2015 to allow more than 1 wing 
            /*for(String strPlant : mapPlantCodeWing.keyset())
            {
                if(mapPlantCodeWing.get(strPlant).size() > 1){
                    blnIncorrectPlantMapping = true;
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Same plant code is mapped to more than one wing.'));
                    break;
                }
                
            }*/
            
            if(!blnIncorrectPlantMapping){
                if(!listWingToUpdate.isEmpty())
                    Database.Saveresult[] result = Database.update(listWingToUpdate);
                Database.Saveresult[] resultProjectName = Database.update(listProject);
            }
        }
    }
    
    // Cancel Method
    public PageReference cancel(){
        stdController.cancel();
        return ApexPages.currentPage();
    }
    
    // Inner class for mapping wing and plant code selection
    public class WingPlantCodeMapping{
        
        public Wing__c objWing {get; set;}
        public String strPlantCode {get; set;}
        
        public WingPlantCodeMapping(){
            objWing = new Wing__c();
            strPlantCode = '';
        }
    }
    
    //method to perform callout to the SAP Webservice
    public String callInventoryService(Id pProjectId){
    
        String returnMsg = '';
        
        SAPINTPlantCodeGeneration.ZSD_FM_GET_PLANT_SFDC_IDResponse_element objResponse = 
                                                        new SAPINTPlantCodeGeneration.ZSD_FM_GET_PLANT_SFDC_IDResponse_element();
        
        SAPINTPlantCodeGeneration.ZSD_FM_GET_PLANT_SFDC_ID oGetPlantSfdcId = new SAPINTPlantCodeGeneration.ZSD_FM_GET_PLANT_SFDC_ID();
        
        oGetPlantSfdcId.inputHttpHeaders_x = new Map<String,String>(); 
        
        String strAuthorizationHeader = 'Basic ' + Encodingutil.base64Encode(Blob.valueOf(SAP_AUTH_USERNAME + ':' + SAP_AUTH_PASSWORD));
        oGetPlantSfdcId.inputHttpHeaders_x.put('Authorization', strAuthorizationHeader);
        
        //Siddharth 1.1
        String strProjectId = (String.valueOf(pProjectId)).subString(0,15);
        System.debug('========== Project Id ' + strProjectId);
         
        objResponse = oGetPlantSfdcId.ZSD_FM_GET_PLANT_SFDC_ID(strProjectId, new SAPINTPlantCodeGeneration.TABLE_OF_ZSDT_COMP_PLNT1_STRU());
        System.debug('=========== Response ' + objResponse);
        
        for(SAPINTPlantCodeGeneration.ZSDT_COMP_PLNT1_STRU item1 : objResponse.IT_OUTPUT.item){
            System.debug('================== item ' + item1);
        }
        
        System.debug('===================== BAPIRET 1 ' + objResponse.RETURN_x);
        
        if(objResponse != null){
            listPlantCode = new List<String>();
            if(objResponse.IT_OUTPUT != null){
                if(objResponse.IT_OUTPUT.item != null){
                    for(SAPINTPlantCodeGeneration.ZSDT_COMP_PLNT1_STRU item : objResponse.IT_OUTPUT.item){
                        listPlantCode.add(item.WERKS);
                    }
                 //mrunali gaonkar.  
                for(SAPINTPlantCodeGeneration.ZSDT_COMP_PLNT1_STRU item1 : objResponse.IT_OUTPUT.item){
                    System.debug('================== item ' + item1);
                    if(item1.VKORG != null){
                      listProject[0].Sales_Organization__c = item1.VKORG;
                    }
                }
                    //listProject[0].Sales_Organization__c = objResponse.IT_OUTPUT.item[0].VKORG;
                    system.debug('Sales_Organization__c@@'+listProject[0]+'objResponse##'+objResponse.IT_OUTPUT.item[0].VKORG);
                    blnResponseForPlantCode = true;
                }
                else{
                    blnResponseForPlantCode = false;
                    returnMsg = 'No plant codes returned from SAP.';
                }
            }
        }
        return returnMsg;
    }
}
Leslie  KismartoniLeslie Kismartoni
HttpCallouts don't actually work when running tests (nor do Soap callouts).

Use the Test.isRunTest() method to find out if the code being executed is part of a Unit Test. If this call returns true, then return some premade/pre-populated data with some conditions/results you want.

Specifically, I'd probably trap on the oGetPlantSfdcId.ZSD_FM_GET_PLANT_SFDC_ID() callout.

Since I don't know what your objResponse object really looks like, I won't evern try to think of how to popualte it. Suffice to say, if you can trap a real callout, then maybe save the output, that might help as a more plausible seed.

Hope this helps... 
James LoghryJames Loghry
Leslie's incorrect in that you should use the WebserviceMock interface for this, as your subject suggests.  It's a best practice to shy away from using Test.isRunningTest at all costs, unless you absolutely have to.  

In order to get WebserviceMock to work, you'll need to create a separate class that implements the WebserviceMock interface as shown in the first example on this page: 
https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_callouts_wsdl2apex_testing.htm

The response.put('response_x', respElement); piece is key, as this tells salefsorce what to expect from the soap callout.

Also key is using the Test.setMock(WebServiceMock.class, new YourWebServiceMockImpl()); in your Test class, which will tell Salesforce to inject your mock response into the unit test instead of performing an actual callout.

Hope that helps.

 
Leslie  KismartoniLeslie Kismartoni
Stand corrected --> James' way is better.