Комментарии:
I like it. As a minimum, I almost always create a static CreateSut() in the test class I use in my tests to instantiate the SUT. If there is ever a change to ctor parameters, I just have to change the CreateSut method.
If there are "arrange steps" that are reused between tests, I'll usually just have CreateSutWithXxx() static methods, where Xxx is some description of the state the SUT is placed into, e.g. if testing a shopping cart, it could be CreateSutWithSingleItemAdded(). Makes the arrange step easier to understand at a glance.
I reach for more general builder patterns mentioned in this video if tests for a single SUT is split between test classes.
That is an ideal use case for Builders, well done!
And thanks for sharing.
After years of using the Builder Design Pattern to setup testdata I have found a better solutoin: C# records. I create a static method that instantiates a "default" instance of a record and with the "with" operator I setup further properties. This way I don't have to create Builder classes with all their properties and methods while I maintain the same functionality.
ОтветитьThank you for this great content, Gui!
Do you think it is ok to set private fields with Reflection in the Build method to get the object in the needed state for the test? Or do you prefer an internal constructor/factory method that can be called trough the InternalsVisibleTo option? Or is there any other option?
I prefer to go with factory method with private constructor ...
ОтветитьI can see that the Directors might be needed in more complex situations. But instead of creating multiple Directors for each pizza type, wouldn't it be simpler to just add a fluent method "StartWith(PizzaBuilder.PizzaType.Plain)" that takes in a class specific enum? I know this would place the responsibility of the default configuration as part of the Builder, but it would make sense here to simplify code maintenance and readability. You can still create the directors later if you want that control somewhere else.
Thanks for all the great content.
I really like using this approach in my own tests, actually
ОтветитьAwesome ! Definitely I will try this on unit tests , can we apply this integration tests ?
Ответитьpizza without cheese is not a pizza))
ОтветитьYay design patterns! I love your accent by the way. "Margherita Director" has such beautiful pronunciation. I will definitely be using the builder pattern to help reduce redundancy in my tests. Thank you!
Ответить