I'm writing unit tests and for one of them i have to use a community user, to get the Network.

I used the following mock:

public enum PortalType { CSPLiteUser, PowerPartner, PowerCustomerSuccess,     CustomerSuccess }

public static User getPortalUser(PortalType portalType, User userWithRole, Boolean doInsert) {
    /* Make sure the running user has a role otherwise an exception
       will be thrown. */
    if(userWithRole == null) {  
        if(UserInfo.getUserRoleId() == null) {
            UserRole r = new UserRole(name = 'TEST ROLE');
            userWithRole = new User(alias = 'hasrole', email='userwithrole@roletest1.com', userroleid = r.id,
                                emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
                                localesidkey='en_US', profileid = UserInfo.getProfileId(),
                                timezonesidkey='America/Los_Angeles', username='userwithrole@testorg.com');
        } else {
            userWithRole = new User(Id = UserInfo.getUserId(), UserRoleId = UserInfo.getUserRoleId());
        System.assert(userWithRole.userRoleId != null,
                      'This test requires the target org to have at least one UserRole created. Please create a user role in this organization and try again.');
    Account a;
    Contact c;
    System.runAs(userWithRole) {
        a = new Account(name = 'TEST ACCOUNT');
        c = new Contact(AccountId = a.id, lastname = 'lastname');
    /* Get any profile for the given type.*/
    Profile p = [select id
                  from profile
                 where usertype = :portalType.name()
                 limit 1];  

    String testemail = 'puser000@amamama.com';
    User pu = new User(profileId = p.id, username = testemail, email = testemail,
                       emailencodingkey = 'UTF-8', localesidkey = 'en_US',
                       languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles',
                       alias='cspu', lastname='lastname', contactId = c.id);

    if(doInsert) {
    return pu;

I read through Apex Testing with RunAs,and used the code in a test method and when System.RunAs(pu), the Network.getNetworkId method returns null.

User pu = testUtils.getPortalUser(testUtils.PortalType.PowerPartner, null, true);
    System.debug('User PU ' + pu);

    system.debug(pu.isPortalEnabled); //returns false
    system.debug([select isPortalEnabled
                  from user
                  where id = :UserInfo.getUserId()].isPortalEnabled);
                                                               //returns true
    string communityId = Network.getNetworkId(); // returns null

What Im missing to get that Network.getNetworkId?

Even if i query the user that returns isPortalEnabled = true and run as that user, the Network is still null. Tried to query a Sys Admin and run as that user, still null.

  • 1
    You will get much more helpful feedback if you link to whatever resources you "found on the internet". – Adrian Larson Nov 13 '16 at 15:31
  • Struggling with same issue here... trying to figure out how to have Apex Test run as if it were in the context of a Community, not just run as a Community User. – Doug Ayers Mar 15 '17 at 4:38
  • As follow up, this article says you can query NetworkMember object to get the ID even though Network.getNetworkId() will continue to return null. developer.salesforce.com/forums/?id=906F00000005KqvIAE – Doug Ayers Mar 26 '17 at 7:51

When the Community User is created given its profile, it is automatically assigned to the NetworkMember object

This is basically a junction object between the Network (Community) and the User (community member)

This Sobject can be queried:

NetworkMember membership = [SELECT NetworkID, MemberID FROM NetworkMember
                              WHERE memberID = :pu.id];

and hence membership.NetworkId gets you what you want whereas in test context, Network.getNetworkId() returns null.

See also use in FeedItems use case


See the Network Object in the Object Reference.

Use this object to find, view, and update communities in your organization. If you have “Modify All Data,” “View All Data,” or “Create and Set Up Communities,” you can view all communities in the organization. Users without these permissions only see the Preview or Published communities that they’re members of. If you have “Create and Set Up Communities,” you can customize community settings.

Unless your RunAs user has the necessary permissions referenced above, you won't be able to obtain the Community's NetworkId.


As the above didn't solve your issue, I see something else in your code that may be the source of the problem. The Network Class is just like the list class, pagereference class, map class, etc. To use it, you need to create a new instance of it using a constructor.

Try changing your code as follows:

Network MyCommunity = new Network();

string communityId = MyCommunity.getNetworkId();

If the above doesn't resolve your issue, you'll need to post more of your code.

  • Even if i change the profile to sys admin, that has all the permissions, the result is still the same. – Zhan Levov Nov 14 '16 at 6:21
  • When i create a Network object it is empty, no id, nothing, even if i create it RunAs(user) – Zhan Levov Nov 16 '16 at 6:14

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.