function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
RyanhRyanh 

Testing Best Practices -- Reusable code in unit tests?

Given that unit test methods are required to be static and void, I find that I have a lot of duplicated code for the test setup. If I write 3 unit tests for one method because there are different branches in the logic of that method, I'm copying and pasting the data setup portion of the test case into each of the three unit tests.

 

There's gotta be a better way! Help? Ideas?

 

Thanks 

Best Answer chosen by Admin (Salesforce Developers) 
JimRaeJimRae

I have struggled with this as well. The solution I came up with, not ideal, but better than nothing, was to create an additional "setuptest" method that does all of my object creation.  I create top level static variables and objects and then populate them with my setuptest method execution.

For each branch unit test, I call the setuptest method, and the objects are created.

All Answers

JimRaeJimRae

I have struggled with this as well. The solution I came up with, not ideal, but better than nothing, was to create an additional "setuptest" method that does all of my object creation.  I create top level static variables and objects and then populate them with my setuptest method execution.

For each branch unit test, I call the setuptest method, and the objects are created.

This was selected as the best answer
RyanhRyanh
I was thinking about the same approach, but if you mark that method as a "testMethod", don't you need an "assert" statement in there? And if you don't, you'd have to write unit tests against that, wouldn't you?
JimRaeJimRae
I tried it both ways.  If you don't declare the setup as a testmethod, it appears to need testing, I get good coverage, not 100% since I have some try catch blocks for sobject creation. When I do declare it as a testmethod, it appears to work fine.  I have some asserts in my catch blocks, but hope they never get executed.