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
Manu ErwinManu Erwin 

Enabling Communities? Be aware average code coverage <75%

Thinking of enabling #Communities for your customer? Then be aware of the current #Gotcha that the default Apex Classes that are created when you enable your first Community do not ALL have code coverage >75%.

What this means:
You can enable Communities in Production, however as soon as you attempt to migrate anything from a sandbox into Production that triggers all tests to be run (doesn't have to be just code), your migration will fail as three of the classes only have 33%, 20% and 21%.

Let me repeat that, you might only be migrating a bunch of new custom fields and page layouts and the Change Set (or Eclipse/ANT) will fail.

I hit this problem this week in a go-live deployment so had to update Apex Classes to achieve average total code coverage >75% in order to proceed with our deployment.

The PM of Communities knows about the problem and advises he is looking at a fix, but in the meantime here are the four Apex Classes that need to be updated.

 

CommunitiesLandingControllerTest.cls

Just a one liner for this test class

/**
 * An apex page controller that takes the user to the right start page based on credentials or lack thereof
 */
@IsTest public with sharing class CommunitiesLandingControllerTest {
  @IsTest(SeeAllData=true) public static void testCommunitiesLandingController() {
    // Instantiate a new controller with all parameters in the page
    CommunitiesLandingController controller = new CommunitiesLandingController();

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    PageReference pageRef = controller.forwardToStartPage();
  }
}

 

CommunitiesLoginControllerTest.cls

Just a one liner for this test class

/**
 * An apex page controller that exposes the site login functionality
 */
@IsTest global with sharing class CommunitiesLoginControllerTest {
  @IsTest(SeeAllData=true) 
  global static void testCommunitiesLoginController () {
    CommunitiesLoginController controller = new CommunitiesLoginController ();

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    PageReference pageRef = controller.forwardToAuthPage();
  }  
}

 

CommunitiesSelfRegControllerTest.cls

A few controller variables to set prior to calling the controller method for the original test method, followed by a couple of additional test methods for further coverage.

/**
 * An apex page controller that supports self registration of users in communities that allow self registration
 */
@IsTest public with sharing class CommunitiesSelfRegControllerTest {
  @IsTest(SeeAllData=true) 
  public static void testCommunitiesSelfRegController() {
    CommunitiesSelfRegController controller = new CommunitiesSelfRegController();

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    controller.firstName = 'Bob';
    controller.lastName = 'Jones';
    controller.email = 'bob@jones.com';
    controller.password = '8yhMsHDN&ituQgO$WO';
    controller.confirmPassword = '8yhMsHDN&ituQgO$WO';
    controller.communityNickname = 'bob-jones-testing';

    PageReference pageRef = controller.registerUser();
  }
  // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
  @IsTest(SeeAllData=true) 
  public static void testInvalidPassword() {
    CommunitiesSelfRegController controller = new CommunitiesSelfRegController();
    controller.firstName = 'Bob';
    controller.lastName = 'Jones';
    controller.email = 'bob@jones.com';
    controller.password = '8yhMsHDN&ituQgO$WO';
    controller.confirmPassword = 'not the same';
    controller.communityNickname = 'bob-jones-testing';

    PageReference pageRef = controller.registerUser();
    System.assert(pageRef == null, 'The returned page reference should be null');
  }
  // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
  @IsTest(SeeAllData=true) 
  public static void testNullPassword() {
    CommunitiesSelfRegController controller = new CommunitiesSelfRegController();
    controller.firstName = 'Bob';
    controller.lastName = 'Jones';
    controller.email = 'bob@jones.com';
    controller.communityNickname = 'bob-jones-testing';

    PageReference pageRef = controller.registerUser();
    System.assert(pageRef == null, 'The returned page reference should be null');
  }
}

 

CommunitiesSelfRegController.cls

A few additions to this class to set the Profile and Account Ids for portal user creation. Update the ProfileId value based on the "portal" license(s) (e.g., Customer Portal, Customer Community, etc) and set the AccountId to that of the Account you wish to use for self-registration. Note: this needs to be set even if you're not using self-registration so the class can be tested.

Plus some debug statements so I could see what was happening and needed to be tested.

/**
 * An apex page controller that supports self registration of users in communities that allow self registration
 */
public with sharing class CommunitiesSelfRegController {

  public String firstName {get; set;}
  public String lastName {get; set;}
  public String email {get; set;}
  public String password {get; set {password = value == null ? value : value.trim(); } }
  public String confirmPassword {get; set { confirmPassword = value == null ? value : value.trim(); } }
  public String communityNickname {get; set { communityNickname = value == null ? value : value.trim(); } }
  
  public CommunitiesSelfRegController() {}
  
  private boolean isValidPassword() {
    return password == confirmPassword;
  }

  public PageReference registerUser() {
  
    // it's okay if password is null - we'll send the user a random password in that case
    if (!isValidPassword()) {
      System.debug(System.LoggingLevel.DEBUG, '## DEBUG: Password is invalid - returning null');
      ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, Label.site.passwords_dont_match);
      ApexPages.addMessage(msg);
      return null;
    }  

    // 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    //String profileId = ''; // To be filled in by customer.
    //String roleEnum = ''; // To be filled in by customer.
    //String accountId = ''; // To be filled in by customer.

    // Set this to your main Communities Profile API Name
    String profileApiName = 'PowerCustomerSuccess';
    String profileId = [SELECT Id FROM Profile WHERE UserType = :profileApiName LIMIT 1].Id;
    List<Account> accounts = [SELECT Id FROM Account LIMIT 1];
    System.assert(!accounts.isEmpty(), 'There must be at least one account in this environment!');
    String accountId = accounts[0].Id;
    
    String userName = email;

    User u = new User();
    u.Username = userName;
    u.Email = email;
    u.FirstName = firstName;
    u.LastName = lastName;
    u.CommunityNickname = communityNickname;
    u.ProfileId = profileId;
    
    String userId = Site.createPortalUser(u, accountId, password);
   
    if (userId != null) { 
      if (password != null && password.length() > 1) {
        System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation successful and password ok - returning site.login');
        return Site.login(userName, password, null);
      }
      else {
        System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation successful but password not ok - redirecting to self reg confirmation');
        PageReference page = System.Page.CommunitiesSelfRegConfirm;
        page.setRedirect(true);
        return page;
      }
    }
    System.debug(System.LoggingLevel.DEBUG, '## DEBUG: User creation not successful - returning null');
    return null;
  }
}

 

 

t_Christ_Chris
Thanks for posting this, saved a lot of time,
rickwallenbrockrickwallenbrock

Thanlks for the post.  This is amazing that Salesforce does not deply their own stuff with adequate code coverage.  Until I found this post I spent about an hour and half trying to do a 5 mintue job.  I still can't get it  to work as I am not sure what roleEnum is.

 

Jen BennettJen Bennett
The roleEnum is the Role set on a community user record.
rickwallenbrockrickwallenbrock
Great thanks

--
Rick Wallenbrock
Redcote Consulting, Inc.
510-409-4660 (m)
www.redcote.com
jill.longojill.longo

Thanks for posting. I see for the CommunitiesSelfRegController you note that the AccountID needs to be updated, but I can't find where to add the ID. I'm an admin and are trying to troubleshoot this on my own. Assistance is greatly appreciated.

 

Jen BennettJen Bennett

I have a test partner account and used their account ID to set it In this section of the code...

// 25-Jun-2013 Manu Erwin - Fixing insufficient code coverage for default Communities Apex Tests
    //String profileId = ''; // To be filled in by customer.
    //String roleEnum = ''; // To be filled in by customer.
    //String accountId = ''; // To be filled in by customer.
YoniYoni

Thank you for this! You are a lifesaver!

Forza di SognoForza di Sogno

Thanks!  It seems packaging a solution which has communities enabled is really challenging. Do your above steps help to deploy packages as well? In packages SeeAllData will be ignored and this leads to very low coverage as all Community-related classes using ConnectApi will fail.  Have you come across this scenario?  What would your recommend to overcome this issue?

LiefoLiefo

Hey Folks.

 

I'm still struggling with this.

 

So do I need to uncomment the following three lines of code and add in values for each line?

 

//String profileId = ''; // To be filled in by customer.
//String roleEnum = ''; // To be filled in by customer.
//String accountId = ''; // To be filled in by customer.

 

e.g. Changed to be the following (still unsure what to put for roleEnum - will null work?)

 

String profileId = '00eE0000000edXM'; // To be filled in by customer.
String roleEnum = 'null'; // To be filled in by customer.
String accountId = '001E000000faTHI'; // To be filled in by customer.

LiefoLiefo

Apparently the only change required is as follows. Wish it hadn't taken me hours to find this out! Make sure you have one account created in your sandbox at least.

 

Uncomment this line of code and enter the profileId of your main communities profile in production:

 

String profileId = '00eE0000000edXM'; // To be filled in by customer.

 

Comment the following line of code as shown below:

 

//String profileId = [SELECT Id FROM Profile WHERE UserType = :profileApiName LIMIT 1].Id;

MIKE_DAYMIKE_DAY
THANK YOU EVER SO MUCH!!!!!  ALL OF MY TEST CLASSES WERE ABOVE 85% AND THIS WAS KILLING ANY NEW TRIGGERS APPLIED.  ALL FIXED.
HayaHaya
I am new at deployment and am strugling with the: Average test coverage across all Apex Classes and Triggers is 55%, at least 75% test coverage is required.
You wrote: The PM of Communities knows about the problem and advises he is looking at a fix
Do you know if a fix is available?
Thank you,
Haya
Manu ErwinManu Erwin
Hi Haya, this problem only applied when a previous release upgraded existing environments. Are you experiencing a problem with these specific Test Classes for Communities OR test coverage in general? Take a look at our recommended best practices regarding test coverage - https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_testing_best_practices.htm
Andy TheimerAndy Theimer
I also have code coverage issues with Chatter Answers enabled on the following 2 triggers:
ChatterAnswersAuthProviderRegistration = 0%
chatter_answers_question_escalation_to_case_trigger = 35%

Any ideas on these guys?

Manu ErwinManu Erwin
@Andy Theimer - unsure about those specific classes sorry. Have you looked at the specific code that is not being executed in order to figure out what needs to be changed?
MoosecoutureMoosecouture
Andy,

I see that this issue has been resolved in the Post https://developer.salesforce.com/forums/ForumsMain?id=906F0000000A4tAIAS (https://developer.salesforce.com/forums/ForumsMain?id=906F0000000A4tAIAS" target="_blank) but I am still having a hard time tracking down a test for "ChatterAnswersAuthProviderRegistration" does anybody have a solution to the 0% code coverage for this Class?
James Gordon 10James Gordon 10
Folks, there is a bit of a workaround for this.  If you are deploying a trigger, for example, make sure the specific test class is included in the changeset.  Upload the changeset > click "validate" in production > select Run Specified Tests.  (NOT "Default")

This basically allows you to sidestep overall org coverage and have your changeset be validated independently.  If the changeset has 75% coverage, it will pass and be available for quick deploy.
renanfamousrenanfamous
Thnks man, u saved the day.
Ch SalmanCh Salman
Having a sewing machine with a wide range of stitch lengths and widths is essential for upholstery work. It allows you to tailor your stitches to different fabrics and create sturdy seams. a fantastic read (https://sofiasewing.com/best-heavy-duty-sewing-machine/)
MartinezMartinez
Hi, I hope you all are doing well.
Thanks for sharing this useful information I really like this and it helps (https://docs.google.com/spreadsheets/d/1kh9_FZTtMZpxZi3N6va4UOvnVUMxxUvLDx_NYnw8gnM/edit#gid=0) me a lot.