I do not want users from a 'XYZ' profile to access a VF page. I have removed the permission from profile level for that page.

Functionality is working correctly and the user gets insufficient privileges error.

I want to build an apex test around this functionality.

When trying to run the test method as 'XYZ' profile user I am able to update the record (Ideally it should not happen).

Upon checking other questions found this thread - How do I find out if a user has access to a visualforce page through apex?

Is this the only way or do we have a better way of testing the scenario?

  • Have you tried Page.GetContent running as a test user with the disallowed profile? I've never tested it so I don't want to post as an answer until I do. Commented Jan 29, 2020 at 22:17

1 Answer 1


I think that perhaps you can take an approach a bit more user friendly.. just a though. Giving the users the Insufficient privileges error. is not really a great experience.

You can use your Constants Helper Class, if you have one... it not, is a good reason to start building one?

Lest say you have your constants class with something like this:

public without sharing class MyConstants {

    // Profiles
    public static final String SYS_ADMIN_PROFILE = 'System Administrator';
    public static final String STANDARD_USER = 'Standard';

You can add as many constants as you need for those profiles.

If this is ready you can just add to your controller something like this.

private static Set <String> userProfiles = new Set <String> {

That set will contain the profiles you need for your logic within the controller. That set should be a member variable. Right below your class declaration.

On the methods that you are using in your class logic in which you want to check if a user is or not authorized for any particular operation you can add something like this:

// Add your logic 
Profile profile = [
                    SELECT Id, Name
                    FROM Profile
                    WHERE Id = :UserInfo.getProfileId()

Boolean correctProfile = userProfiles.contains(profile.Name);

   if (!correctProfile) {
   ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'Your Message'));

When you run your test with System.runAs('User with wrong Profile'); in your test class just assert that the error is equal to the one you are using to inform the user on the page. Just make sure that your page has the tag <apex:Messages/> to get messages expose to the page. This will not redirect the user to Insufficient privileges error page but it will inform the user on the same page that he can't do whatever action you are not allowing him to do based on the profile.

You must log in to answer this question.

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