1
@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
}

在正常运行页面时,控制器返回正确的网络 ID,当尝试为此编写测试类时,社区网络 ID 始终返回 null。

4

1 回答 1

1

您用于 runAs 的用户需要是社区的一部分,因此您需要创建一个帐户,创建一个联系人,然后为该联系人创建一个用户。这使得 runAS 用户成为社区的一部分

于 2018-08-16T20:32:30.310 回答