Annotate your test class or test method with IsTest(SeeAllData=true) to open up
data access to records in your organization.
This example shows how to define a
test class with the
isTest(SeeAllData=true) annotation. All the test methods in this class have access to all
data in the organization.
@isTest(SeeAllData=true)
public class TestDataAccessClass {
static testmethod void myTestMethod1() {
Account a = [SELECT Id, Name FROM Account WHERE Name='Acme' LIMIT 1];
System.assert(a != null);
Account testAccount = a.clone();
testAccount.Name = 'Acme Test';
insert testAccount;
Account testAccount2 = [SELECT Id, Name FROM Account
WHERE Name='Acme Test' LIMIT 1];
System.assert(testAccount2 != null);
}
@isTest static void myTestMethod2() {
}
}
This second example shows how to apply
the
isTest(SeeAllData=true) annotation on a test method. Because the class that the test method
is contained in isn’t defined with this annotation, you have
to apply this annotation on the test method to enable access to all
data for that test method. The second test method doesn’t have
this annotation, so it can access only the data it creates in addition
to objects that are used to manage your organization, such as users.
@isTest
private class ClassWithDifferentDataAccess {
@isTest(SeeAllData=true)
static void testWithAllDataAccess() {
}
@isTest static void testWithOwnDataAccess() {
User u = [SELECT UserName,Email FROM User LIMIT 1];
System.debug('UserName: ' + u.UserName);
System.debug('Email: ' + u.Email);
Account a = new Account(Name='Test Account');
insert a;
Account insertedAcct = [SELECT Id,Name FROM Account
WHERE Name='Test Account'];
System.assert(insertedAcct != null);
}
}
- Considerations for the IsTest(SeeAllData=true) Annotation
-
- If a test class is defined with
the isTest(SeeAllData=true) annotation, this annotation applies to all its test methods whether
the test methods are defined with the @isTest annotation or the testmethod keyword.
- The isTest(SeeAllData=true) annotation is used to open up data access when applied at the class
or method level. However, using isTest(SeeAllData=false) on a method doesn’t restrict organization data access for
that method if the containing class has already been defined with
the isTest(SeeAllData=true) annotation. In this case, the method will still have access to all
the data in the organization.