Writing unit tests is one thing, but making them maintainable and easy to ready is another. Fortunately, the builder pattern was defined to deal with both of those concerns. This tutorial will show you why the builder pattern is a design pattern that’s extremely important in unit testing.
The builder pattern and more so the fluent syntax is a great resource. I use it everyday and not just for testing, domain too.
Here is how our tests look at dayjob. I like my synstax around running same command twice ![]()
Given(db => /* Setup here */)
.When().Query<SearchQuery>().WithDate(_date)
.And(result => bookingKey = result.First().BookingKey).Command<ReserveCommand>().WithBookingKey(bookingKey)
.And().Command<ConfirmCommand>().WithBookingKey(bookingKey)
.And().Command<CancelCommand>().WithBookingKey(bookingKey)
.Repeat()
.Twice()
.Then(db => db.Set<Booking>().SingleOrDefaultAsync(b => b.BookingKey == bookingKey));
Above searches for a flight. Takes the first available flight and stores it booking key. Then it reserves the flight, and right after confirms it. And lastly cancel it, twice to test that it does not crash domain to cancel twice.
edit: I need to impove how results from queries are sent to builers though. Not nice to need to store it as private member of test like I do above