Pragmatic Test-Driven Development in C# and .NET by Adam Tibi

Pragmatic Test-Driven Development in C# and .NET by Adam Tibi

Author:Adam Tibi
Language: eng
Format: epub
Publisher: Packt Publishing Ltd.
Published: 2022-09-23T00:00:00+00:00


The builder pattern

For the same SUT, every unit test’s arrangement varies slightly from others. The builder design pattern is useful when creating an object with lots of possible configuration options, which comes in handy for this scenario.

Note

This is different from the Gang of Four (GoF) Builder design pattern.

The builder class, for the previous example, looks like this:

public class OneCallResponseBuilder { private int _days = 7; private DateTime _today = new (2022, 1, 1); private double[] _temps = {2, 3.3, 4, 5.5, 6, 7.7, 8}; public OneCallResponseBuilder SetDays(int days) { _days = days; return this; } public OneCallResponseBuilder SetToday(DateTime today) { _today = today; return this; } public OneCallResponseBuilder SetTemps(double[] temps) { _temps = temps; return this; } public OneCallResponse Build() { var res = new OneCallResponse(); res.Daily = new Daily[_days]; for (int i = 0; i < _days; i++) { res.Daily[i] = new Daily(); res.Daily[i].Dt = _today.AddDays(i); res.Daily[i].Temp = new Temp(); res.Daily[i].Temp.Day = _temps.ElementAt(i); } return res; } }

What is notable in this class is that:

Every method returns the class instance. This helps to chain methods like this:OneCallResponse res = new OneCallResponseBuilder()

.SetDays(7)

.SetTemps(new []{ 0, 3.3, 0, 0, 0, 0, 0 })

.Build();



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.