When testing can I not use existing Data?

I am currently programming a trigger on Opportunities.

I created a test class for this and in my Sandbox I created an account, contact and opportunity. When I try to reference them

Opportunity Opp = [SELECT id from Opportunity where name = 'Test1']; 

and then start my

        Opp.StageName = 'PO in (100%)'; 
        update Opp; 

It just errors and shows that Opp returns 0 rows. However when I paste my first bit of code in ‘Execute Anonymous’ it returns a row and the correct info.

Does this mean I have to create an account, contact, quote and all necessary fields in my test class?


Do not use existing data. It is a terrible practice for it and there is almost never a need to do it. Using existing data will cause serious issues whenever you create a new sandbox or attempt to move any code to a different organization.

It is considered a very bad practice. There is a reason Salesforce removed the ability to access data from the system by default in version 24. Problems like – UNABLE_TO_LOCK_ROW error while running all apex test classes – pop up when running asynchronous tests. Avoid those problems now and write the tests with the best practice right out the gate.

Here is some good documentation on writing unit tests. There is also Isolation of Test Data from Organization Data in Unit Tests.

EDIT: A common practice my coworkers and I have used is creating a TestUtils class and using that class to create the data model. That would allow you to do something like:

public class TestUtils{
    public static Account getAccount(){
        Account acc = new Account(Name = 'Account');
        insert acc;
        return acc;

then from your test method:

public class TestClass{
    static testMethod void myTest() {
        Account acc = TestUtils.getAccount();

This will generate an account, insert it into the DB, and then return it to be used in the test. This can then be reused around the system.

Source : Link , Question Author : jnoel10 , Answer Author : Community

Leave a Comment