I’m studying TDD and experimenting it in my current project.
I’ve noticed that I have to duplicate a lot of asserts in my tests.
Here is situation:
I have Order class with two constructors first one is default and
second one has three params
Order(int customerId, int typeId, decimal amount)
In the OrderTests class I’m checking that assignments are working well
Assert.IsTrue(o.CustomerId == 5 && o.TypeId == 3 && amount == 500)
I have order service class with following create order method as order creation is complex process.
Order CreateOrder(int cusotmerId, int typeId, int amount, moreParams...)
OrderServiceTests class has test for this method and I need to use same assert to check that Order has been created correctly in the CreateOrder service.
Assert.IsTrue(o.CustomerId == 5 && o.TypeId == 3 && amount == 500)
- Is it ok to have such duplications in Tests?
- Is it make sense to extract methods with same assertions in tests as sometimes number or duplicated asserts maybe more then one? Or such method extractions make tests unreadable?
If you have multiple ways to create an object, you might want to test the object’s state for each of the creation methods (i.e. parametrized constructor as well as factory method). Thus it makes sense to duplicate the assertions.
During refactoring after making your test pass (always remember the mantra: red-green-refactor) if you find duplication not only in your production code but also in your tests, then you should remove it by e.g. using the Extract Method refactoring.
It complicates things if you check multiple conditions within one Assert statement as in your example. It reduces test readability and it might be difficult to find the cause if any one of the conditions fails.