Organising unit-test data

How do you organise the data for your unit tests? In most non-trivial applications you will have a fairly complex domain model. Again and again you will find yourself needing to create instances of such complex objects for your tests.
Over the time I’ve used 3 methods for this:

  1. Copy-Paste. It’s quick, and being unit-tests it’s not such a no-go. It also keeps tests independent of one another (as opposed to method 2). The downside is when you need to update the test data, for example if you add a new field – you’ll need to go over all the copies and update them.
  2. TestDataHelper. Have a class with static methods that create and pre-fill your objects with data. For any updates you only need to change one place. The downside is that it couples your tests between them. If you need different data for one test, and you change your Helper class, it may break other tests.
  3. TestBuilders. This is my favourite method right now. You create builder classes for your complex objects, with parametrised methods for child objects. This way you have one central place to make changes, but your tests are independent, as they don’t share data.
    Here’s an example:

    Catalog catalog = new CatalogBuilder()
    	.addProduct("Chair", "Wood")
    	.withCategory("Furniture")
    	.withCategory("Kitchen")
    	.addProduct("Sofa", "Leather")
    	.withCategory("Furniture")
    	.withCategory("Living Room")
    	.build();
    

Which method do you use?

Leave a Reply

Your email address will not be published. Required fields are marked *