I have a controller for a VF Page in a SF Community that returns data from the logged-in user's related Contact record. These user accounts are generated by starting with a contact, then creating a Customer Community Login user account to give them access to the community, so all User accounts that will be viewing this page will have an associated Contact record.

I'm running into trouble testing it because when I run the tests I'm logged in as my own user account in the Sandbox console, and I don't see a way to attach a Contact record to an existing User account. So when the test hits this line

this.userContact = [SELECT Id, Name, AccountId from Contact WHERE Id = :user.ContactId];

then this.userContact is always null and it can't complete the rest of the test.

How can I fix this? Either by associating a Contact record with my existing SF admin user account in the Sandbox, or if that's not possible, is there a better way to write either the controller or the test to work around this?

When I first wrote the test my VF page was set up differently, so I was just inserting dummy data in the test (contacts, users, etc) and then passing the id of the dummy user to the VF page as a parameter. But now that the controller is using :UserInfo.getUserId() to get the id of the logged in user (which is the only way I've been able to get this to work on the front end), I can't figure out how to update my test to match.


public with sharing class UserStewardListController {

    private final User user;
    private final Contact userContact;
    public final Account userAccount;
    private final CVRSOS__Local__c sublocal;
    private final Id sublocalId;

    public UserStewardListController(ApexPages.StandardController stdController) {
        System.debug(LoggingLevel.INFO, '>>> UserStewardListController');
        this.user = [SELECT Id, ContactId FROM User WHERE Id = :UserInfo.getUserId()];
         System.debug(LoggingLevel.INFO, '>>> USER' + user);
         this.userContact = [SELECT Id, Name, AccountId from Contact WHERE Id = :user.ContactId];

       System.debug(LoggingLevel.INFO, '>>> USER CONTACT' + userContact);

            this.userAccount = [SELECT Id, Name, Sublocal__c, Organizer_Name__c, Organizer_Email__c, Organizer_Cell_Phone__c from Account WHERE Id = :userContact.AccountId];
            System.debug(LoggingLevel.INFO, '>>> USER ACCOUNT' + userAccount);

                this.sublocal = [SELECT Id from CVRSOS__Local__c where Id = :userAccount.Sublocal__c];
                this.sublocalId = sublocal.Id;
                System.debug(LoggingLevel.INFO, '>>> SUBLOCAL' + sublocal);
                System.debug(LoggingLevel.INFO, '>>> SUBLOCALID' + sublocalId);


    public List<CVRSOS__LocalSteward__c> getStewards() {
        System.debug(LoggingLevel.INFO, '>>> getStewards');
        CVRSOS__LocalSteward__c[] stewardList = [
            SELECT  Id,
            FROM    CVRSOS__LocalSteward__c
            WHERE   ( CVRSOS__LocalId__c = :this.sublocalId)
        if(stewardList.size() > 0) {
            System.debug(LoggingLevel.INFO, '>>> stewardList' + stewardList);
            return stewardList;
        } else {
            System.debug(LoggingLevel.INFO, '>>> stewardList.size === 0');
            return null;


    public Account getUserAccount() {
        return userAccount;


private class UserStewardListControllerTest {

    static testMethod void testMethod1(){
            //Insert Sublocal Record 
            CVRSOS__Local__c s = new CVRSOS__Local__c(Division__c='Care Providers');
            list<CVRSOS__Local__c> sublocalList = new list<CVRSOS__Local__c>();
            System.debug(LoggingLevel.INFO, '>>> sublocalList' + sublocalList);
            insert sublocalList;

            // Save sublocalId for creating Account
            Id sublocalId = sublocalList[0].Id;

           //Insert Account and Contacts
           Account a = new Account(Name = 'Test Account');
           Insert a;

           Contact c1 = New Contact(AccountId = a.Id, FirstName='FirstName1', LastName='LastName1', CVRSOS__Local__c = sublocalId);
           Contact c2 = New Contact(AccountId = a.Id, FirstName='FirstName2', LastName='LastName2', CVRSOS__Local__c = sublocalId);
           Contact c3 = New Contact(AccountId = a.Id, FirstName='UserFirst', LastName='UserLast', CVRSOS__Local__c = sublocalId);
           Insert c1;
           Insert c2;
           Insert c3;

           //Insert User

           User u = New User(Contact=c3, ContactId=c3.Id);

            //Insert Stewards
            CVRSOS__LocalSteward__c st1 = new CVRSOS__LocalSteward__c(  CVRSOS__ContactId__c = c1.Id, CVRSOS__LocalId__c = sublocalId);
            CVRSOS__LocalSteward__c st2 = new CVRSOS__LocalSteward__c(  CVRSOS__ContactId__c = c2.Id, CVRSOS__LocalId__c = sublocalId);
            list<CVRSOS__LocalSteward__c> stewardList = new list<CVRSOS__LocalSteward__c>();
            System.debug(LoggingLevel.INFO, '>>> stewardList' + stewardList);
            insert stewardList;


            PageReference pageRef = Page.UserContactSublocalStewardList; 
            pageRef.getParameters().put('id', String.valueOf(u.Id));

            ApexPages.StandardController sc = new ApexPages.StandardController(u);
            UserStewardListController ext = new UserStewardListController(sc);

            //Test that Stewards are Inserted
            list<CVRSOS__LocalSteward__c> obj1 = ext.getStewards();
            // system.assertequals(obj1.size(),2);

            //Delete Records
            delete sublocalList;
            delete stewardList;
            delete a;
            delete c1;
            delete c2;
            delete c3;        

            //Test that Stewards are Deleted
            list<CVRSOS__LocalSteward__c> obj2 = ext.getStewards();


  • see this blog post for an approach - you need to create a valid community user and runAs that user.
    – cropredy
    Feb 25, 2020 at 22:44

1 Answer 1


Unit tests run in system context mode when executed, should you wish to run a test as a specific user you can use

system.runAs(User){ //code to be executed as this user }

Its worth pointing out that you will likely want to insert the user rather than creating on the fly as the user id you set here will be null.

pageRef.getParameters().put('id', String.valueOf(u.Id));

One thing worth noting in this case is given you are testing as a community user you should ensure the user you are running as is a community user with the right profile / licence type.

Im going to assume you are using the Customer Community Licence here. A quick check of the LicenseDefinitionKey attribute on the UserLicence object shows that the LicenseDefinitionKey for Customer Community Licence is PID_Customer_Community

Armed with this knowledge you should be able to query for any profiles associated to that licence and assign to the user.

List<Profile> customerCommunityProfiles = [SELECT ID FROM Profile WHERE Profile.UserLicense.LicenseDefinitionKey = 'PID_Customer_Community'];

Further more you will need to specify the PortalRole for the user before you insert. In order to do this without tripping yourself up you will want to ensure the system context user creating the test community user has a role assigned themselves within Salesforce otherwise you may run into

Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Invalid role assignment.: []

Hope this helps.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .