In a new post to his site Robert Basic shows how to make use of traits to create test doubles in your unit testing practice. He sees them as a simple method for keeping tests clean and not having mocks/fakes/etc. all over.
Keeping your application or library code well organized, easy to follow, and read is important. Your test code should not be exempt from those rules, you should follow good testing conventions.One part of my tests that I feel like that are out of control are the test doubles. Dummies, fakes, mocks… Seems like they are everywhere and that I keep writing the same ones over and over again. I do follow some good practices on how to reduce code duplication in my tests, but these mocks… Ugh.
He starts with a simple example, showing a test that evaluates the result of a transaction being executed (true or false). However, he describes the eventual "creep" of the tests as more are added and, with each, more "transaction" object instances are required. He suggests refactoring the creation of those doubles into traits where the class they're called from can inherit them and test setup is a bit cleaner. He proposes a "trait for every double" so that they can be easily included as needed and without conflict.