function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
MonikaalladaMonikaallada 

Run Test is not giving me the right statement.(instead of test failure, test success is the output).

This is my test class

@isTest
public class testAccountdetails
{
static testMethod void testAccountdetails()
{

Accountdetails ad = new Accountdetails();

ad.Aname='GenePoint';
List<contact> cn = ad.getcodetails();
if(!cn.isEmpty()){
for( contact c : cn){
System.assertEquals('Edna Fra',c.LastName);// here test must fail but no error.
}
}

 

Apex class:

 

public class Accountdetails
{

public String Aname;

public List<contact> getcodetails()
{

cc =[select name ,Email from Contact where Account.name=:Aname ];
return cc;
}
}

 

According to this i should get a test failure because in the system.assertEqual i gave a wrong contact name.

Instead of that test is success, 

 

Can any one please tell where the mistake is.

Best Answer chosen by Admin (Salesforce Developers) 
vishal@forcevishal@force

I see that you have not created any test records. What is your class API version?

 

If it's 24 or more, your code won't enter the for loop at all, so there's no way a failure will be thrown.

 

Ideal solution:

 

Create a test Account record with that name, create a Contact for that Account and run your test.

 

And yes, it should be your API version that is the reason. You don't get access to Org records from a test method in classes having v24 or above.

All Answers

PrakashbPrakashb

Are you sure the Contact which is getting returned is not the one you are expecting.

 

Can you do a system.debug on your Contact and check the contact information??

vishal@forcevishal@force

I see that you have not created any test records. What is your class API version?

 

If it's 24 or more, your code won't enter the for loop at all, so there's no way a failure will be thrown.

 

Ideal solution:

 

Create a test Account record with that name, create a Contact for that Account and run your test.

 

And yes, it should be your API version that is the reason. You don't get access to Org records from a test method in classes having v24 or above.

This was selected as the best answer
MonikaalladaMonikaallada

Thank you vishal

 

This happened when i replace IsTest annotation with IsTest(SeeAllData=true).

vishal@forcevishal@force

It's nice that it worked for you.

 

However, it is not the ideal way. Suppose you don't have any record in your database, in such a case even (SeeAllDAta = true) will not help.

 

So the best practice is to not depend on any data, create all the data you want within your test classes.

MonikaalladaMonikaallada

yup,

 

yes if the record is not present in our database, it wont work right.

 

can you please give me any example how can we create and test in our own test classes.

 

even simple code also no issue.