• julienb
  • NEWBIE
  • 0 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 1
    Replies

Hi, 

 

I got the following class with testmethod that does not support service call out. 

I trying to change the testmethod to use mock responce but i must admin i'm quite new to apex... 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_callouts_wsdl2apex_testing.htm

 

can someone please help ? 

thank you, 

Julien

 

/**
 * An apex page controller that exposes the site login functionality
 */
global with sharing class PortalLoginController 
{
  private User userRecord;
  
    global String OrgId            {get; private set;}
    global String CustomerPortalHostname {get; private set;}
    global String CustomerPortalId     {get; private set;}
    global String PartnerPortalHostname  {get; private set;}
    global String PartnerPortalId       {get; private set;}
    global String StartUrl         {get; private set;}    
    global Boolean IsPartner         {get; private set;}
  global String Username         {get; set;}
    global String Password         {get; set;}
    
    global PortalLoginController() 
    {
        this.OrgId = UserInfo.getOrganizationId(); 
        this.IsPartner = false;        
        
        loadPortalInfo();        
    }
    
    private void loadPortalInfo()
    {
      List<SitesToPortalsRedirectSettings__c> settings = SitesToPortalsRedirectSettings__c.getAll().values();
      
      if(settings.size() == 0 || settings.size() > 2)
      {
        if(settings.size() > 2)
        {
          throw new CustomException('Too many portals have been setup in the SitesToPortalsRedirectSettings custom setting.');
        }
        else
        {
          throw new CustomException('No portals have been setup in the SitesToPortalsRedirectSettings custom setting.');
        }  
      }
      
      Integer partnerPortalCount = 0;
      Integer customerPortalCount = 0;
      
      for(SitesToPortalsRedirectSettings__c setting : settings)
      {
        if(setting.Is_Partner_Portal__c == true)
        {
          partnerPortalCount++;
        }
        else
        {
          customerPortalCount++;
        }
      }
      
      if(partnerPortalCount > 1)
      {        
        throw new CustomException('Too many partner portals have been setup in the SitesToPortalsRedirectSettings custom setting.');      
      }
      
      if(customerPortalCount > 1)
      {        
        throw new CustomException('Too many customer portals have been setup in the SitesToPortalsRedirectSettings custom setting.');      
      }
      
      //If we get here, all checks above passed
      for(SitesToPortalsRedirectSettings__c setting : settings)
      {
        if(setting.Is_Partner_Portal__c == true)
        {
          this.PartnerPortalHostname = setting.Portal_Hostname__c;
            this.PartnerPortalId = setting.Portal_Id__c;
        }
        else
        {
          this.CustomerPortalHostname = setting.Portal_Hostname__c;
            this.CustomerPortalId = setting.Portal_Id__c;
        }
      }
    }
    
    private void LoadUserRecord()
    {
      List<User> userRecords = [select Id, UserType from User where Username = :Username];
      
      if(userRecords.size() != 1)
      {
        return;
      }
      
      this.userRecord = userRecords[0];
      
      if(userRecord == null)
      {
        throw new CustomException('No user was found for username: ' + Username);
      }
      
      if(userRecord.UserType != null && userRecord.UserType.trim().length() > 0)
      {
        if(userRecord.UserType.trim().equalsIgnoreCase('PowerPartner') == true)
        {
          this.IsPartner = true;
        }
        else
        {
          //Assume customer portal user
        }
      }
      else
      {
        //Should never see this but there just in case
        throw new CustomException('No UserType has been specified for the user with a username of ' + Username);
      }
    }     
    
    //This ensures we have a protocol and the trailing slash at the end of the hostname
    private String getCleanedHostname(String hostname)
    {
      if(hostname == null || hostname.trim().length() == 0)
      {
        throw new CustomException('getCleanedHostname - A hostname is required');
      }
      
      if(hostname.trim().startsWith('http://') == false || hostname.trim().startsWith('https://') == false)
      {
        //Assume SSL
        //hostname = 'https://' + hostname;
      }
      
      if(hostname.trim().endsWith('/') == false)
      {
        hostname = hostname + '/';
      }
      
      return hostname;
    }   

    global PageReference login() 
    {
      loadUserRecord();
        
        this.StartUrl = System.currentPageReference().getParameters().get('startURL');
        
        String hostname = null;
        String portalId = null;
        String urlString = null;
        
        if(StartUrl == null || StartUrl.trim().length() == 0)
        {
            List<String> values = new List<String>();
            
            if(IsPartner == true)
            {
              hostname = PartnerPortalHostname;
              portalId = PartnerPortalId;
              urlString = '{0}secur/login_portal.jsp?orgId={1}&portalId={2}&un={3}&pw={4}';
            }
            else
            {
              hostname = CustomerPortalHostname;
              portalId = CustomerPortalId;
              urlString = '{0}secur/login_portal.jsp?orgId={1}&portalId={2}&un={3}&pw={4}';
            }
            
            hostname = getCleanedHostname(hostname);
            
            values.add(hostname);
            values.add(orgId);
            values.add(portalId);
            values.add(username);
            values.add(password);                                                
            
            this.StartUrl = String.format(urlString, values);
        }
        
        System.debug('### START URL = ' + StartUrl);
        
        HttpRequest request = new HttpRequest();
        
        request.setEndpoint(StartUrl);
        request.setMethod('GET');
        
        /*      
        Blob headerValue = Blob.valueOf(username + ':' + password);
        
        String authorizationHeader = 'BASIC ' +
        
        EncodingUtil.base64Encode(headerValue);
        
        req.setHeader('Authorization', authorizationHeader);
        */
        
        Http http = new Http();
        
        HTTPResponse response = http.send(request);
     
        debugResponse(response);        
        
        if(response.getStatusCode() == 200)
        {                
            return new PageReference(hostname + 'home/home.jsp');
        }
        else if(response.getStatusCode() == 302)
        {                
            return new PageReference(response.getHeader('Location'));
        }
        else
        {
            return null;
        }
        
        //return Site.login(username, password, startUrl);
    }          
    
    private void debugResponse(HttpResponse response)
    {
      if(response == null)
      {
        return;
      }
      
      UDebug.printDebug('BODY = ' + response.getBody());      
      UDebug.printDebug('STATUS = ' + response.getStatus());
      UDebug.printDebug('STATUS CODE = ' + response.getStatusCode());
      
      for(String key : response.getHeaderKeys())
      {              
        if(key != null && key.trim().length() > 0)
        {
          String header = response.getHeader(key);
          
          UDebug.printDebug(key + ' = ' + header);
        }
      }
    } 
    
    public class CustomException extends Exception {}
        
    @IsTest(SeeAllData=true) 
    global static void testPortalLoginController () 
    {        
        Integer portalSettingsRowCount = [select count() from SitesToPortalsRedirectSettings__c];
        
        if(portalSettingsRowCount == 0)
        {
          SitesToPortalsRedirectSettings__c setting = (SitesToPortalsRedirectSettings__c) USObject.getCustomSetting('SitesToPortalsRedirectSettings__c');
          
          setting.Portal_Hostname__c = 'http://www.test.test';
          setting.Portal_Id__c = '123';
          
          insert setting;
        }
        
        PortalLoginController controller = new PortalLoginController ();
        controller.username = 'test@salesforce.com';
        controller.password = '123456'; 
                
        System.assertEquals(controller.login(),null);                           
    }       
}

 

 

Hi, 

 

I got the following class with testmethod that does not support service call out. 

I trying to change the testmethod to use mock responce but i must admin i'm quite new to apex... 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_callouts_wsdl2apex_testing.htm

 

can someone please help ? 

thank you, 

Julien

 

/**
 * An apex page controller that exposes the site login functionality
 */
global with sharing class PortalLoginController 
{
  private User userRecord;
  
    global String OrgId            {get; private set;}
    global String CustomerPortalHostname {get; private set;}
    global String CustomerPortalId     {get; private set;}
    global String PartnerPortalHostname  {get; private set;}
    global String PartnerPortalId       {get; private set;}
    global String StartUrl         {get; private set;}    
    global Boolean IsPartner         {get; private set;}
  global String Username         {get; set;}
    global String Password         {get; set;}
    
    global PortalLoginController() 
    {
        this.OrgId = UserInfo.getOrganizationId(); 
        this.IsPartner = false;        
        
        loadPortalInfo();        
    }
    
    private void loadPortalInfo()
    {
      List<SitesToPortalsRedirectSettings__c> settings = SitesToPortalsRedirectSettings__c.getAll().values();
      
      if(settings.size() == 0 || settings.size() > 2)
      {
        if(settings.size() > 2)
        {
          throw new CustomException('Too many portals have been setup in the SitesToPortalsRedirectSettings custom setting.');
        }
        else
        {
          throw new CustomException('No portals have been setup in the SitesToPortalsRedirectSettings custom setting.');
        }  
      }
      
      Integer partnerPortalCount = 0;
      Integer customerPortalCount = 0;
      
      for(SitesToPortalsRedirectSettings__c setting : settings)
      {
        if(setting.Is_Partner_Portal__c == true)
        {
          partnerPortalCount++;
        }
        else
        {
          customerPortalCount++;
        }
      }
      
      if(partnerPortalCount > 1)
      {        
        throw new CustomException('Too many partner portals have been setup in the SitesToPortalsRedirectSettings custom setting.');      
      }
      
      if(customerPortalCount > 1)
      {        
        throw new CustomException('Too many customer portals have been setup in the SitesToPortalsRedirectSettings custom setting.');      
      }
      
      //If we get here, all checks above passed
      for(SitesToPortalsRedirectSettings__c setting : settings)
      {
        if(setting.Is_Partner_Portal__c == true)
        {
          this.PartnerPortalHostname = setting.Portal_Hostname__c;
            this.PartnerPortalId = setting.Portal_Id__c;
        }
        else
        {
          this.CustomerPortalHostname = setting.Portal_Hostname__c;
            this.CustomerPortalId = setting.Portal_Id__c;
        }
      }
    }
    
    private void LoadUserRecord()
    {
      List<User> userRecords = [select Id, UserType from User where Username = :Username];
      
      if(userRecords.size() != 1)
      {
        return;
      }
      
      this.userRecord = userRecords[0];
      
      if(userRecord == null)
      {
        throw new CustomException('No user was found for username: ' + Username);
      }
      
      if(userRecord.UserType != null && userRecord.UserType.trim().length() > 0)
      {
        if(userRecord.UserType.trim().equalsIgnoreCase('PowerPartner') == true)
        {
          this.IsPartner = true;
        }
        else
        {
          //Assume customer portal user
        }
      }
      else
      {
        //Should never see this but there just in case
        throw new CustomException('No UserType has been specified for the user with a username of ' + Username);
      }
    }     
    
    //This ensures we have a protocol and the trailing slash at the end of the hostname
    private String getCleanedHostname(String hostname)
    {
      if(hostname == null || hostname.trim().length() == 0)
      {
        throw new CustomException('getCleanedHostname - A hostname is required');
      }
      
      if(hostname.trim().startsWith('http://') == false || hostname.trim().startsWith('https://') == false)
      {
        //Assume SSL
        //hostname = 'https://' + hostname;
      }
      
      if(hostname.trim().endsWith('/') == false)
      {
        hostname = hostname + '/';
      }
      
      return hostname;
    }   

    global PageReference login() 
    {
      loadUserRecord();
        
        this.StartUrl = System.currentPageReference().getParameters().get('startURL');
        
        String hostname = null;
        String portalId = null;
        String urlString = null;
        
        if(StartUrl == null || StartUrl.trim().length() == 0)
        {
            List<String> values = new List<String>();
            
            if(IsPartner == true)
            {
              hostname = PartnerPortalHostname;
              portalId = PartnerPortalId;
              urlString = '{0}secur/login_portal.jsp?orgId={1}&portalId={2}&un={3}&pw={4}';
            }
            else
            {
              hostname = CustomerPortalHostname;
              portalId = CustomerPortalId;
              urlString = '{0}secur/login_portal.jsp?orgId={1}&portalId={2}&un={3}&pw={4}';
            }
            
            hostname = getCleanedHostname(hostname);
            
            values.add(hostname);
            values.add(orgId);
            values.add(portalId);
            values.add(username);
            values.add(password);                                                
            
            this.StartUrl = String.format(urlString, values);
        }
        
        System.debug('### START URL = ' + StartUrl);
        
        HttpRequest request = new HttpRequest();
        
        request.setEndpoint(StartUrl);
        request.setMethod('GET');
        
        /*      
        Blob headerValue = Blob.valueOf(username + ':' + password);
        
        String authorizationHeader = 'BASIC ' +
        
        EncodingUtil.base64Encode(headerValue);
        
        req.setHeader('Authorization', authorizationHeader);
        */
        
        Http http = new Http();
        
        HTTPResponse response = http.send(request);
     
        debugResponse(response);        
        
        if(response.getStatusCode() == 200)
        {                
            return new PageReference(hostname + 'home/home.jsp');
        }
        else if(response.getStatusCode() == 302)
        {                
            return new PageReference(response.getHeader('Location'));
        }
        else
        {
            return null;
        }
        
        //return Site.login(username, password, startUrl);
    }          
    
    private void debugResponse(HttpResponse response)
    {
      if(response == null)
      {
        return;
      }
      
      UDebug.printDebug('BODY = ' + response.getBody());      
      UDebug.printDebug('STATUS = ' + response.getStatus());
      UDebug.printDebug('STATUS CODE = ' + response.getStatusCode());
      
      for(String key : response.getHeaderKeys())
      {              
        if(key != null && key.trim().length() > 0)
        {
          String header = response.getHeader(key);
          
          UDebug.printDebug(key + ' = ' + header);
        }
      }
    } 
    
    public class CustomException extends Exception {}
        
    @IsTest(SeeAllData=true) 
    global static void testPortalLoginController () 
    {        
        Integer portalSettingsRowCount = [select count() from SitesToPortalsRedirectSettings__c];
        
        if(portalSettingsRowCount == 0)
        {
          SitesToPortalsRedirectSettings__c setting = (SitesToPortalsRedirectSettings__c) USObject.getCustomSetting('SitesToPortalsRedirectSettings__c');
          
          setting.Portal_Hostname__c = 'http://www.test.test';
          setting.Portal_Id__c = '123';
          
          insert setting;
        }
        
        PortalLoginController controller = new PortalLoginController ();
        controller.username = 'test@salesforce.com';
        controller.password = '123456'; 
                
        System.assertEquals(controller.login(),null);                           
    }       
}