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?
It's the same as with any reusable code, just create another class and add your method:
You can then call this method from any of your other test methods to setup data:
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:
Then in your test class,
And reference the account as
Variations are obviously possible, this is a start...
Just an addition to LaceySnr's answer. It was not available at the time of question and answers but was added in Spring '15 release. It is pretty cool and in my opinion worth mentioning.
It's called Test Setup Methods.
You can create a seperate method that creates data for all test methods before they are run - they are inserted into database and can be fetched later in each method. So if you need to create a lot of test data around opportunities (many DML operations) it might be more efficient to create them this way. Changes made to each record in any test method are not affecting other test methods - they are made just in scope of that test method.
To use this approach you need to implement @testSetup
Documentation can be found here: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_testsetup_using.htm
I use a slightly different approch than LaceySnr. Instead of using static records my creator classes return them as sObject lists. Depending on your needs of course. If you want different test classes use the same data, then LaceySnr's answer is the way to go for. If not and you want to edit the records created by the creator class slightly or you simply want your insert statement within your test class, you could do the following:
Dependencies like Record Type IDs would have to be set up as static variable/collection beforehand if you use them.