For the project my team and me are working on we often find that we need large pieces of scaffolding code. Creating domain objects with correct values, setting up mocks for repositories, dealing with the cache,... are all things that occur commonly throughout the tests. A lof of times we're working with the same basic objects that are central to our domain (person,...) so lots of tests create instances of these objects for other objects to work on. We have a lot of different solutions using the base domain so this kind of code is often spread across those solutions.I've been thinking about creating common classes that do a lot of this scaffolding. This would allow us to request a fully instantiated person with everything set up (access via repository, caching...). This removes duplicate code from our individual unit tests but would also mean there is a large amount of code that probably does 'too much' per test (as it would set up a full object and not just the parts required).Has anyone ever done this? Are there any insights, remarks, thoughts... you can offer that might validate or invalidate this approach?
Advantages and disadvantages to making common unit test scaffolding code
unit testing;tdd
All the possibilities summed up in the answers:Use the Builder pattern (Bedwyr Humphreys, DXM and Pascal Mestdach)Advantages:No code duplication in testsCan combine different builders for complex testsClean interfaceBig object graphs from builders can influence test outcomeDisadvantages:Builders must be written and maintainedBuilder code must be tested as wellBuilder code will need constant grooming and attentionUse a test database (Tony Hopkinson and Sam)Advantages:SimplicityAll data in one central placeCan use data-acces code already developedUsable for domain objects that are not POCO (eg. Active Record,...)Disadvantages:Requires the use of the DAL wich might interfere with testsNot 'pure' TDD'Black box', need to take a look at the database to see what data your objects containCreate domain objects per test (Peter)Advantages:Isolated test codeNo 'black box', what you see in the test code is what you getDisadvantages:Code duplication for common objectsUse Facades for domain objects (Raedwald)Advantages:Simple testsDisadvantages:Not usable in all casesCode hidden behind Facade needs testing as well