7

I'm learning how to write tests to improve the code coverage of my Apex classes. In the official documentation on the subject the examples show how a test fixture is set up before the test to make the tests portable by inserting sample data into your tables to test against, like:

static testMethod void myTestDynamicIds(){

     // CORRECT - Create the required test data needed for the test scenario.
     // In this case, I need to update an Account to have a BillingState='CA'
     // So I create that Account in my test method itself.
     Account testAccount = new Account(name='Test Company Name');
     insert testAccount;

     testAccount.billingState='CA';
     update testAccount;

     // now do the test....
}

Yet this test record in never removed. When tests are run on the production org, do the tests then leave test data like this in the production database? Should you write code to remove the fixture?

Given this code example, what does it mean when the documentation say:

Test methods take no arguments, commit no data to the database, and cannot send any emails.

Any clarification will be appreciated and eagerly voted up.

8

Data inserted in test is never saved into the database.

Since a few releases ago tests by default execute in the seealldata=false, which means that during the test they do not have read access to the real data. This is good because it means you set up your full test data correctly and you don't have any risk of a conflict, e.g. trying to insert a test record which happens to have the same unique key that a real record has.

Old api version tests and tests with seealldata=true have access to work with the data currently in your org, BUT this is never saved after the test has finished running.

If you get into testing web services, you will find that you code making calls out does not actually make the call out when it is executed as part of a test. Salesforce has provided some methods for mocking up the results. You don't need to worry that your test will send spurious data to your external system though.

The only "contamination" is that you will find that autonumber fields increment. So for example if your highest record is autonumber A-000100, then you run a test which inserts a record, after the test runs you will find that

  1. there is no sign of the test data. It is not committed.
  2. the next real insert you do is number A-000102
  • You should note that the "contamination" of auto-numbers can be avoided by submitting a case to salesforce.com, but that this behavior is actually a feature to stop tests from locking out users while the test runs. – sfdcfox Sep 20 '13 at 18:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.