function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Andries.NeyensAndries.Neyens 

How to Unit Test a Community User

I,m trying to write some unit tests for a community user but it seems that I am doing something wrong with the security:

 

In my controller I do the following (I compressed the code a bit ;-) :

 

 

public class MyController


...


Id aId =[SELECT Id, Contact.AccountId FROM User WHERE Id=: UserInfo.getUserId() LIMIT 1].Contact.AccountId;

List<Opportunity> oppties = [SELECT ... FROM Opportunity WHERE AccountID =: aID];


... 

 

 

Now you are all thinking; hang on, a community user has no access to the opportunities!

That is correct, hence the class definition without the 'with sharing' and afterwards I put the opportunities in a wrapper..

 

Anyhow, this is working perfectly with a correct community user, created via a contact of an account ()

 

 

Now the test:

 

// add an account

// add a contact to that account

// create a user connected to that contact, with the profile of the community user

// Create 10 opportunities on that account

 

System.runAs(theUser) {
	System.assert([select UserType from user where id = :UserInfo.getUserId()].UserType == 'CSPLitePortal');
        	
        	Test.startTest();    	
        	MyController controller = new MyController();
    	Test.stopTest();
    		
    	//We should have 10 wrapped opportunities
    	System.AssertEquals(10, controller.Opportunities.size());
}

 

The first assert works, assuming the user is correctly made?

no errors, but the second assert fails that it does not find any opportunies.

Ofcourse the second assert works if i run it as an admin.

 

Is there something I'm missing ???

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Andries.NeyensAndries.Neyens

ok, found it!!

 

Seems that the class definition:

 

public class MyController is not correct in all cases (not in unit test context)

 

(http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_keywords_sharing.htm)

 

What I had to do is change it into:

 

public without sharing class MyController

 

to make sure that the sharing rules are not enforced !!!