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='test123@test.com',
                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='tester@test.com');

        insert user;



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

            Test.stopTest();
        }


    }
}
Hello World
  • 169
  • 1
  • 2
  • 11

1 Answers1

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.

crmprogdev
  • 40,955
  • 9
  • 58
  • 115