Find your content:

Search form

You are here

Possible error in Select statement

 
Share

I have written a customer controller for a VisualForce page which displays all the Contact records associated with a particular Account. When manually testing the VisualForce page everything seems to work fine. All of the Contacts are displayed as I want them to be.

However, when I write some test code, my SELECT statement doesn't pull out my test Contact that I've associated with my test Account. I'm wondering whether it is to do with the way that I have written my SELECT statement.

My SELECT statement:

[SELECT Id, FirstName, LastName, Email, Salutation, Title, Primary__c, To_Be_Deleted__c 
                    FROM Contact 
                    WHERE Contact.Account.Id = :accountID
                    AND To_Be_Deleted__c = false];

Some setup code in my test class:

Account acc = new Account(name = 'Test Account');
Contact validPrimaryContact = getValidActiveContact();
validPrimaryContact.Primary__c = true;
validPrimaryContact.Account = acc;

insert acc;
insert validPrimaryContact;

Debugging Log showing that no rows have been found for that select statement:

16:00:36.448 (1448431000)|CONSTRUCTOR_ENTRY|[18]|01pP000000058yE|<init>(String,String)
16:00:36.448 (1448781000)|METHOD_ENTRY|[28]|01pP000000058yE|ContactCleanupController.init()
16:00:36.448 (1448858000)|USER_DEBUG|[38]|DEBUG|accountID: 001P000000Z1iPjIAJ
16:00:36.448 (1448901000)|USER_DEBUG|[39]|DEBUG|returnID: 001P000000Z1iPjIAJ
16:00:36.448 (1448925000)|METHOD_ENTRY|[40]|01pP000000058yE|ContactCleanupController.selectOnlyActiveContacts()
16:00:36.449 (1449424000)|SOQL_EXECUTE_BEGIN|[130]|Aggregations:0|select Id, FirstName, LastName, Email, Salutation, Title, Primary__c, To_Be_Deleted__c from Contact where (Contact.Account.Id = :tmpVar1 and To_Be_Deleted__c = false)
16:00:36.456 (1456474000)|SOQL_EXECUTE_END|[130]|Rows:0

Not sure what I'm doing wrong here. Is it something to do with Contact.Account.Id?

Many thanks


Attribution to: Joe

Possible Suggestion/Solution #1

Yes, you should insert the account and then assign the Id to the contact. So I'd rearrange thus:

Account acc = new Account(name = 'Test Account');
insert acc;    

Contact validPrimaryContact = getValidActiveContact();
validPrimaryContact.Primary__c = true;
validPrimaryContact.Account = acc.Id;

insert validPrimaryContact;

Also, I don't know what you're doing in getValidActiveContact() but be aware that you have no access to existing contacts in your org for the duration of the test. Therefore if you haven't explicitly inserted a new contact that will likely return nothing.


Attribution to: Joel Mansford
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/1112

My Block Status

My Block Content