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
davcondevdavcondev 

runOnce and test methods

Does anyone have a solution for the following situation:
  • Trigger uses a static runOnce boolean class variable to prevent recursive firing
  • Test method creates data that fires the trigger and runOnce is set
  • Test method then performs a DML operation but the trigger doesn't fire because runOnce is already set
In real usage the data creation and the DML operation would never occur in the same context and the trigger should fire twice, so an assert fails.

The only way I can think of to get around this is to fudge the assert to match the test-only result, or use @SeeAllData=true and rely on preexisting data - neither very satisfactory.
Best Answer chosen by davcondev
bob_buzzardbob_buzzard
Is there any reason why you can't clear down the runOnce boolean value once you have carried out your test setup?  For example, if you delineate your test setup with a test.startTest() call, you could then set the value of the runOnce boolean at the same time with a suitable comment to explain what you are doing.

Or you could have a method on your runOnce class of 'resetAfterTestSetup()' if you don't want to expose the internal workings.

This seems like reasonable dependency injection for testing behaviour to me.  

All Answers

bob_buzzardbob_buzzard
Is there any reason why you can't clear down the runOnce boolean value once you have carried out your test setup?  For example, if you delineate your test setup with a test.startTest() call, you could then set the value of the runOnce boolean at the same time with a suitable comment to explain what you are doing.

Or you could have a method on your runOnce class of 'resetAfterTestSetup()' if you don't want to expose the internal workings.

This seems like reasonable dependency injection for testing behaviour to me.  
This was selected as the best answer
davcondevdavcondev
Thanks for your reply, I ended up adding a method pretty much as you described.