+ Start a Discussion
Jessie Rymph 12Jessie Rymph 12 

help on apex test run as site guest user

@isTest
private class SiteGuestUserTest {
  @TestSetup
  static void testSetup(){
    	Account a = TestFactory.getAccount('boots factory', true);
      	contact c = TestFactory.getContact(a.id,'Connie','Connors', true, 'con@con.com','purchasing');
    
//set up a user with the profile for my site guest user. I read that I don't need to insert the user.
    UserRole userRole = new UserRole(DeveloperName = 'TestingTeam', Name = 'Testing Team');
    String profileName ='Unsubscribe Profile';
    User u = new User(
      ProfileId = [SELECT Id FROM Profile WHERE Name = :profileName].Id,
      LastName = 'last',
      Email = 'Cpt.Awesome@awesomesauce.com',
      Username = 'Cpt.Awesome@awesomesauce.com',
      Profile WHERE Name = 'Guest'] WHERE ID = :ProfileId].id,
      CompanyName = 'Testing Co',
      Title = 'Captain',
      Alias = 'alias',
      TimeZoneSidKey = 'America/Los_Angeles',
      EmailEncodingKey = 'UTF-8',
      LanguageLocaleKey = 'en_US',
      LocaleSidKey = 'en_US'
     
    );

        System.runAs(u) {
              // The following code runs as user 'u'
              System.debug('Current User: ' + UserInfo.getUserName());
              System.debug('Current Profile: ' + UserInfo.getProfileId());
          }
    }
    
    @isTest static void  testPermissionPositive() {
//this test succeeds. the user can see the email address. 
        user u = [SELECT Id from User WHERE LastName = 'last'];
        system.runAs(u){
            Test.startTest();
            Contact connie = [SELECT Id, Email FROM CONTACT WHERE FirstName = 'Connie'];
            Test.stopTest();
            system.assertEquals('con@con.com',connie.Email,'Site Guest User can see the email');
            system.debug(connie.id + connie.Email);
        }
    } 
   //test fails. Site Guest User should not be able to see the department field. 
    @isTest static void  testPermissionNegative() {
        user u = [SELECT Id from User WHERE LastName = 'last'];
        system.runAs(u){
            Test.startTest();
            Contact connie = [SELECT Id, Email, Department FROM CONTACT WHERE FirstName = 'Connie'];
            Test.stopTest();
            system.assertEquals('',connie.Department,'Site Guest User cannot see the department');
            system.debug(connie.id + connie.Department);
        }
    }

I have a site guest user with "Unsubscribe Profile" and I would like to run a test to make sure that it's properly working. The user with this profile should only be able to see the fields Id and Email on the Contact. I believe the second test demonstrates that the guest user is able to see the department field, which they shouldn't. 

Do I need to establish that my user is license type of Guest? Is my premise correct that I can even test this way? What am I missing?
Best Answer chosen by Jessie Rymph 12
AnudeepAnudeep (Salesforce Developers) 
Hi Jessie, 

My suggestion is to verify the read access on a field level for your guest user by running the SOQL query similar to the one below (Append the guest user Id from your org and outside of your test class to the field AssigneeId in the where clause )

SELECT Label, PermissionsTransferAnyLead,
    (SELECT SobjectType, PermissionsRead FROM ObjectPerms where sObjectType ='Contact'),
    (SELECT SobjectType, Field, PermissionsRead FROM FieldPerms),
    (SELECT AssigneeId,Assignee.Name FROM Assignments where Assignee.Name = 'Test Site Guest User')
FROM 
    PermissionSet

OR Use (SeeAllData=true) just for this test and query for guest user directly instead of creating a new user within your test class and confirm if he is able to access Department field 

This will confirm whether the guest user really has or does not have acess to the field and If the user you created in the test class has the same permissions as the guest user

Anudeep

All Answers

AnudeepAnudeep (Salesforce Developers) 
Hi Jessie, 

My suggestion is to verify the read access on a field level for your guest user by running the SOQL query similar to the one below (Append the guest user Id from your org and outside of your test class to the field AssigneeId in the where clause )

SELECT Label, PermissionsTransferAnyLead,
    (SELECT SobjectType, PermissionsRead FROM ObjectPerms where sObjectType ='Contact'),
    (SELECT SobjectType, Field, PermissionsRead FROM FieldPerms),
    (SELECT AssigneeId,Assignee.Name FROM Assignments where Assignee.Name = 'Test Site Guest User')
FROM 
    PermissionSet

OR Use (SeeAllData=true) just for this test and query for guest user directly instead of creating a new user within your test class and confirm if he is able to access Department field 

This will confirm whether the guest user really has or does not have acess to the field and If the user you created in the test class has the same permissions as the guest user

Anudeep
This was selected as the best answer
Jessie Rymph 12Jessie Rymph 12
Anudeep, Thank you for your response. I am not sure how to make the soql query suggestion meet my needs, but your idea to test directly as the guest user has been really helpful. Also, doing more research I learned that RunAs (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_tools_runas.htm?search_text=runAs) is only about sharing settings, not about permissions! I need to be using isAccessible instead! https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_perms_enforcing.htm

You set me in the right direction so I'll give you best answer :)

 
deeraj vengaladeeraj vengala
rocketmail sign in (https://techphiz.net/rocketmail-login-sign-up-yahoo-mail)
Really appreciate this wonderful post that you have provided for us.