NITHESH K
NITHESH K

Reputation: 128

Testing with Community User, getNetworkId return null

@isTest 
public static void TestEmptySearchQuery() {    

    User thisUser = [ select Id from User where Id = :UserInfo.getUserId() ];
        System.runAs ( thisUser ) {     // running as thisUser to Avoid Error: MIXED_DML_OPERATION
        setupData();   // inside setupData, community is created successfully 
        generateUser(); // List of user assigned with some profile, as required for project.  

        list<PermissionSetAssignment> PSA = new  list<PermissionSetAssignment> ();
        PermissionSet ps = [SELECT Id, name FROM PermissionSet where name='Some_Access'];
        system.debug('PermissionSet ' + ps);           
        for(user u:userList)
            PSA.add(new PermissionSetAssignment(AssigneeId = u.id, PermissionSetId = ps.Id));      // all the user assgined with some_access based on requirement of project
        insert PSA;
    }

    Test.startTest(); 
    User usr = [select Id from User where Id = :userList[0].id];

    System.runAs(usr) {
        system.debug('Network ommunityId ****' + Network.getNetworkId());  //getting null 
        SomeClass obj = new SomeClass();
        Id Nid=obj.fetchNetworkId(); // return null;   
        system.debug('network id ' + Nid);  // null
    } 
    Test.stopTest();        
} 

class SomeClass {
//some code
    public id fetchNetworkId() {
        system.debug('network id ' + Network.getNetworkId()); // network id null;
        return Network.getNetworkId(); // return null
    }
    // some code
}

While running normally page, controller returns proper network id, when try to write a test class for this, community network id always return null.

Upvotes: 1

Views: 4304

Answers (1)

Francisco Riccomagno
Francisco Riccomagno

Reputation: 65

the user you use for the runAs needs to be part of a community, so you need to basically create an account, create a contact and then a user for that contact. That makes the runAS user to be part of a community

Upvotes: 2

Related Questions