1

I'm testing a class as a community user. Here is the issue. my debugs show that running user is set. My User query returns a user with a contactid but for some strange reason the contact query is empty. The if statement is executed but no contact is returned. I'm sure I'm missing something very simple.

 public class myClass{
        public myClass(){
            Id runningUserId = UserInfo.getUserId();
            User user = [SELECT Id, ContactId FROM User WHERE Id =: runningUserId AND IsActive =:true][0];

        if(user != null && user.ContactId != null){
           Contact userContact = [select id from Contact where id=:user.ContactId][0];

        }

 }
}

Test Class

 @isTest
private class myClass_Test {

    static testMethod void myTestClass(){

        Id p = [select id from profile where name='Community Profile'].id;

        Account ac = new Account(name =' Community Account') ;
        insert ac; 

        Contact con = new Contact(LastName ='testCon',AccountId = ac.Id);
        insert con;  

        User user = new User(alias = 'test123', email='[email protected]',
                emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
                localesidkey='en_US', profileid = p, country='United States',IsActive =true,
                ContactId = con.Id,
                timezonesidkey='America/Los_Angeles', username='[email protected]');

        insert user;



        system.runAs(user) {
            Test.startTest();
               myClass controller = new myClass();

            Test.stopTest();
        }


    }
}
3
  • what is the OWD model for Contact? What operation is the Community User trying to do upon its related Contact via the VF controller?
    – cropredy
    Dec 13, 2016 at 0:05
  • It's like the community user can't access their own Contact record. Dec 13, 2016 at 0:09
  • Have a read of this answer. It has some details on creating Communities Portal Users, Roles, and Profiles. Dec 13, 2016 at 1:01

1 Answer 1

0

It appears to me the issue is with the code that you're trying to test:

if(user != null && user.ContactId != null){
           Contact userContact = [select id from Contact where id=:user.ContactId][0];

In the above, you're querying for a single Contact record and you've not specified a list, yet you've used [0] at the end of your query as though it was returning a list. That should be removed from your query unless you change the definition to list<Contact>userContact in which case you could leave the [0] at the end of your query.

I recommend you simply remove the [0] instead. If for some reason it won't compile, you can always use limit 1 in your query. That will solve any issues you might have with the compiler so it can resolve the query to a single contact.

You must log in to answer this question.

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