+ Start a Discussion
Adnan PAdnan P 

How to write a test method for user with no access to Opportunity in lookup

Hello,

I'm attempting to write a test method to test a piece of code where a user is attempting to create a custom object record that has an Opportunity lookup on the page layout.  What I'm trying to test is to display an error if the user creating the custom object record does not have access to the related Opportunity.  The error should be displayed when the user clicks 'Save' to save the custom object record.  

What I'm having difficulty with is being able to write the test method and tell it to insert the custom object record but also to make sure that the user does not have access to the Opportunity in the lookup field.  Also, this test class has isTest(SeeAllData=true).

Can someone please point me in the right direction on how this may be accomplished?  Any responses would be greatly appreciated!

sniper of code being tested:
for (Internal_Request__c ir : newInternalRequestList) {
            Opportunity myOpp = oppMap.get(ir.Opportunity__c);
            if (myOpp == null) {
                    ir.addError('You do not have access to this Opportunity or the Opportunity does not exist');
            } else if (invalidStageNameSet.contains(oppMap.get(ir.Opportunity__c).StageName)) {
                    ir.addError('Unable to associate an Opportunity with a "Closed Lost" or "Closed:  No Bid" with an Internal Request.');
                }
            }
Best Answer chosen by Adnan P
Alexander Placidi 86Alexander Placidi 86

Hello Adnan,

you should use seeAllData=true very sparingly. I recommend to create all the test records you need inside a setup method (see @testSetup) annotation. I suggest to create a test profile, which has no access to the opportunity. Then you can easily create a test user with this profile inside the test setup method. 
You can use Test.runAs in order to execute the test in the context of the user. 

I hope this helps.

All Answers

Alexander Placidi 86Alexander Placidi 86

Hello Adnan,

you should use seeAllData=true very sparingly. I recommend to create all the test records you need inside a setup method (see @testSetup) annotation. I suggest to create a test profile, which has no access to the opportunity. Then you can easily create a test user with this profile inside the test setup method. 
You can use Test.runAs in order to execute the test in the context of the user. 

I hope this helps.

This was selected as the best answer
Adnan PAdnan P
Hi Alexander,

Thank you very much for the quick reply.  This is very helpful.  I completely understand that seeAllData=true should be used sparingly.  This is an exisinting class that I'm working with that was mostly written by other devs.  I'm still a novice so I'm trying to understand best practices as I go.

Thanks again!