Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I have multiple Test classes that has duplicate code. One of the methods is to create opportunity records. Can I create a separate class that does this by itself and reference it from the Test classes?

share|improve this question

2 Answers 2

up vote 6 down vote accepted

Short answer:


Long Answer:

It's the same as with any reusable code, just create another class and add your method:

public with sharing class TestUtils
  public static void CreateOppty()
    // create and insert an oppty etc.

You can then call this method from any of your other test methods to setup data:

public static testmethod void SomeTest()
  // do testing

There's an example in the documentation too.

share|improve this answer

You can definitely do this, I always do this for my frequently used objects. You can just create a standard public class and then call it from your test classes. Because it gets called a lot, the test coverage for the class is generally going to be near 100%.

I typically do the following:

public class TestObjects {

// public Lists of freq used objects eg account
public List<Account> accList;

// methods to create a new instance
public void addNewAccount(Account a) {
    if (accList == null) {accList = new List<Account>();}

public static Account newAccountFromData (String accName, Id recType) {
    Account a = new Account(Name = accName, RecordTypeId = recType);
    return a;

Then in your test class,

TestObjects t = new TestObjects();
t.addNewAccount(TestObjects.newAccountFromData('Test acc'));

And reference the account as

Account thisacct = t.accList[0];

Variations are obviously possible, this is a start...

share|improve this answer
If you annotate your TestObjects class with @isTest you don't need to cover it. It would be similar to having a private utility method in a test class itself, not needing coverage. –  Peter Knolle Feb 27 '13 at 1:53
Very true Peter, have amended the answer above - thanks! –  Stephen B Feb 27 '13 at 7:04

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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