Trigger Testing and The Tony Scott Trigger Pattern

Recently, a friend and former colleague of mine posted up a new Force.com cookbook pattern on triggers to help them become more bulkified and streamlined. That pattern can be found Trigger Pattern here. I can verify that this pattern works really well and makes your code work in a far more efficient manner helping you to avoid the ill fated query errors that can occur.

What I also like about Tony’s pattern is how easy it makes unit testing your triggers. You can test triggers in one of two ways; by using DML operations in your test method that will execute the trigger and exercise the code or if implementing the referenced pattern, by preparing an SObject and executing the methods in the trigger handler upon this and asserting upon the manipulated SObject. This will mean that the trigger methods are run in technical terms without context (you cannot get the Trigger.isBefore method to return true outside of a before trigger running) but it is debatable as to whether you need to test this as Salesforce will have previously ensured this is working. You will have achieved more than a sufficient level of code coverage and ensured your code works by unit testing the methods, before doing a full run through of the trigger in systems integration testing.

Myself, Alex Berg and Andy Ogenoff recently were debating with regards to testing practices and how to handle the situation where you have some code that is written about a particular SObject that then changes (a new mandatory field is added for example). This trigger pattern helps your tests to deal effectively with this, allowing you to test correctly factored methods which are not at the mercy of the SObject changing. Someone could change the SObject in this situation, adding a new mandatory field which will cause integration tests to fail. However, your code, which does not rely upon this new field, will still be tested properly and should not fail.

I know that I will be continuing to use this pattern in all of my work.

Tony is currently looking for UK based Force.com contract work. You can find him here on Linkedin. I can highly recommend him.

Share on Twitter, Facebook, Google+
Prev Next