[SalesForce] SOQL query is not working in Test class coverage

I wrote three soql queries in test class

   static testMethod void test_DoGet() {
            RestRequest req = new RestRequest(); 
            RestResponse res = new RestResponse();

            User u = [select id,Lastname,ContactId from user where Contactid != null limit 1]; 
            Contact con = [select id,Lastname,AccountId from contact where id=:u.Contactid];
            Account acc = [select id,name from account where id=:con.AccountID];

            req.httpMethod = 'GET';
            RestContext.request = req;
            RestContext.response = res;            

For the User query, it is returning the user. But for the Account and Contact queries, it is showing System.QueryException: List has no rows for assignment to SObject. I checked in my salesforce edition and it contains many users, Accounts and with contacts.

I tried the above queries like the following.

User u = [select id,Lastname,ContactId from user limit 1]; 
Contact con = [select id,Lastname,AccountId from contact limit 1 ];
Account acc = [select id,name from account limit 1];

Even though it is showing the same error. If these queries is not covered, then i could not complete total coverage.

Best Answer

You have to create your actual test data, I know SeeAllTestData worked but do not do that.

https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods http://www.laceysnr.com/seealldata-why-i-think-you-shouldnt-use/

One reason to not use SeeAllData, lets say your deploying into production. Users are currently inside the org and they are updating accounts. Now when you're trying to deploy the change set the test code runs and by some chance you may also use that account the user is updating, tests will now fail because of row locking and your dead in the water because you're accessing live production data for testing.

Account acc = new Account();
acc.Name = 'Test Name;
insert acc;

Contact con = new Contact();
con.LastName = 'Last Name';
con.AccountID = acc.ID;
insert con;

User u = new User();
u.Lastname = 'Test Name';
u.ContactID = con.ID;
insert u;
Related Topic