5

i am facing problem with getting network id in test class, while executing visual force page, controller returns proper network id, when try to write a test class for this 'ClassNetwork' controller, community network id always return null. Can anyone help me?

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


@isTest(SeeAllData=true)
public static void TestEmptySearchQuery() {    
    Test.startTest(); 
    User u=[select Id,name from user where name ='Alex']; 
    // Registered user from org, same user i login to org through visual force page its working fine. i get the network id in this case.
    System.runAs ( u ) {           
        system.debug('Network communityId ****' + Network.getNetworkId());  //display null 
        ClassNetwork obj = new ClassNetwork();
        Id Nid=obj.fetchNetworkId(); // return null;   
        system.debug('network id ' + Nid);  // Nid is null
    } 
    Test.stopTest();        
} 
3
  • Since your networkId is always null, please check if your user is community user. Network is only available for the community user. Jul 25, 2017 at 5:37
  • @MohitArora , Yes user belongs to a community .
    – NITHESH K
    Jul 25, 2017 at 6:12
  • 1
    Alex is community user, Same user i have logged into salesforce and executed my visual-force page i am able to get network id. but Through Alex user in test class network id is null.
    – NITHESH K
    Jul 25, 2017 at 6:16

1 Answer 1

0

When you create a community user, and the profile used in the community is assigned to the user — a Network Member object record is created in Salesforce.

Thus, if your Alex user has the profile that is related to the community, you can query the corresponding Network Member record filtered by MemberId field, which is the Id of the user, and you can access the NetworkId field from this query, which is the Id of your network.

Id networkId = [SELECT NetworkId FROM NetworkMember WHERE MemberId = :u.Id].NetworkId;

You must log in to answer this question.

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