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

public static void TestEmptySearchQuery() {    
    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
  • Since your networkId is always null, please check if your user is community user. Network is only available for the community user. – Mohit Arora Jul 25 '17 at 5:37
  • @MohitArora , Yes user belongs to a community . – NITHESH K Jul 25 '17 at 6:12
  • 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 '17 at 6:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.