You need to sign in to do that
Don't have an account?
Mike Chandler
How can I retrieve existing Contacts in Unit Tests?
I'm writing unit tests that should be relatively simple, but I'm stumbling over some sort of restriction that I'm unfamiliar with due to my inexperience with Apex. I'm attempting to retrieve usable Contacts from the org to use for testing purposes because I need them to have fully initialized IDs. I'm unable to use test data because inserting them in tests is problematic due to Contact related triggers.
I'm using the following code snippet in my test method and getting exceptions:
I'm annotating my test method as follows, with no luck:
I'm using the following code snippet in my test method and getting exceptions:
Contact testContact = [SELECT Id, FirstName, LastName from Contact LIMIT 1];Error: System.QueryException: List has no rows for assignment to SObject
I'm annotating my test method as follows, with no luck:
@isTest(SeeAllData=true)I'm wondering what I'm missing here. Any ideas how to get a handle on real Contact records for testing purposes?
use @isTest (SeeAllData = TRUE) at class level.
something along these lines;
hope this helps!
All Answers
use @isTest (SeeAllData = TRUE) at class level.
something along these lines;
hope this helps!
Yes, you should not be getting existing record with your code because of below reasons:
1. By dafault the Test Class is annotated with (seeAllData=false), if you don't change this manually to (seeAllData=true).
2. The @isTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method level. However, if the containing class has been annotated with @isTest(SeeAllData=true), annotating a method with @isTest(SeeAllData=false) is ignored for that method. In this case, that method still has access to all the data in the organization. Annotating a method with @isTest(SeeAllData=true) overrides, for that method, an @isTest(SeeAllData=false) annotation on the class.
In your case you can annotate your class or method with (seeAllData=true), this should resolve the problem. Your code should look like below:
Solution 1:
Solution 2:
Both above solution should work for you.
Thanks,
Manish