+ Start a Discussion
Ryan Sloan 7Ryan Sloan 7 

SOQL Query returning 0 Rows

The query
[SELECT Id FROM Contact] 

is returning zero rows in a test class.
I have tried everything I can think of. Why won't it return all records?

When I run the test I am seeing this line in the log.
SOQL_EXECUTE_BEGIN [4]|Aggregations:0|SELECT Id FROM Contact
SOQL_EXECUTE_END     [4]|Rows:0
 
Scott HungScott Hung
Do you have permissions to view the records?  That'd be one reason why you don't get anything...
Paul S.Paul S.
Hi Ryan - have you created contact records in your test class?
Swaraj Behera 7Swaraj Behera 7
Do you insert some Contact records in the test class
Sandy GaliSandy Gali
I know this is not best practice but just for identifying the issue, use SeeAllData = true in your test class
Rakesh51Rakesh51
Either set SeeAllData = true or create few rcords in your test class. As a best practice always create test data
Amit Chaudhary 8Amit Chaudhary 8
Please update your test class like below and create some test record
 
Account acc= new Account();
acc.Name ='test';
insert acc;

Contact cont = new Contact();
cont.firstName ='Test';
cont.lastName ='Test';
cont.accountid = acc.id;
insert cont;

List<Contact> lstCont = [SELECT Id FROM Contact] ;

Let us know if this will help you

Thanks
Amit Chaudhary

 
RACHIT RAKESH 8RACHIT RAKESH 8
Hi,

I think this will help you.
@isTest
public class testClassForContacts{
    private void fetchAllContacts(){
        account accountObj = new account();
        accountObj.name = 'Account Example';
                insert accountObj;
        contact contactObj = new contact();
        contactObj.firstName = 'Contact';
        contactObj.lastName  = 'Example';
        contactObj.accountid = accountObj.id;
               insert contactObj;
        List<contact> listOfContacts = [SELECT Id,accountId FROM Contact] ;
    }
}

Let me know if any queries.

Thanks
RYAN SLOANRYAN SLOAN
Thanks to everyone who replied. I realize now that best practice is to create the test data in my test class and not try to query it from the db.