TestStack.Dossier provides you with the code infrastructure to easily and quickly generate test fixture data for your automated tests in a terse, readable and maintainable way using the Test Data Builder pattern.
For more information please see the blog post that gives the theory behind the approach this library was intended for and the presentation and example code that gives a concrete example of the usage of the library (and the theory behind it).
TestStack.Dossier is integrated with NSubstitute for proxy/mock/substitute object generation and AutoFixture for anonymous value generation. Version 1 was integrated with NBuilder for list generation, but that is now replaced with internal code that uses Castle Dynamic Proxy (il-merged into the dll) for an even terser syntax.
Prior to v2.0 this library was known as NTestDataBuilder.
-
Install-Package TestStack.Dossier -
Create a builder class for one of your domain objects, e.g. if you have a customer:
// Customer.cs public class Customer { protected Customer() {} public Customer(string firstName, string lastName, int yearJoined) { if (string.IsNullOrEmpty(firstName)) throw new ArgumentNullException("firstName"); if (string.IsNullOrEmpty(lastName)) throw new ArgumentNullException("lastName"); FirstName = firstName; LastName = lastName; YearJoined = yearJoined; } public virtual int CustomerForHowManyYears(DateTime since) { if (since.Year < YearJoined) throw new ArgumentException("Date must be on year or after year that customer joined.", "since"); return since.Year - YearJoined; } public virtual string FirstName { get; private set; } public virtual string LastName { get; private set; } public virtual int YearJoined { get; private set; } } // CustomerBuilder.cs public class CustomerBuilder : TestDataBuilder<Customer, CustomerBuilder> { public CustomerBuilder() { // Can set up defaults here - any that you don't set or subsequently override will have an anonymous value generated by default. WhoJoinedIn(2013); } // Note: the methods are virtual - this is important if you want to build lists (as per below) public virtual CustomerBuilder WithFirstName(string firstName) { return Set(x => x.FirstName, firstName); } // Note: we typically only start with the methods that are strictly needed so the builders are quick to write and aren't bloated' public virtual CustomerBuilder WithLastName(string lastName) { return Set(x => x.LastName, lastName); } public virtual CustomerBuilder WhoJoinedIn(int yearJoined) { return Set(x => x.YearJoined, yearJoined); } protected override Customer BuildObject() { return new Customer( Get(x => x.FirstName), Get(x => x.LastName), Get(x => x.YearJoined) ); // or return BuildUsing<CallConstructorFactory>(); } } -
Use the builder in a test, e.g.
var customer = new CustomerBuilder() .WithFirstName("Robert") .Build(); -
Consider using the Object Mother pattern in combination with the builders, see my blog post for a description of how I use this library.
This library allows you to build a list of entities fluently and tersely. Here is an example:
var customers = CustomerBuilder.CreateListOfSize(5)
.TheFirst(1).WithFirstName("First")
.TheNext(1).WithLastName("Next Last")
.TheLast(1).WithLastName("Last Last")
.ThePrevious(2).With(b => b.WithLastName("last" + (++i).ToString()))
.All().WhoJoinedIn(1999)
.BuildList();
This would create the following (represented as json):
[
{
"FirstName":"First",
"LastName":"LastNameff51d5e5-9ce4-4710-830e-9042cfd48a8b",
"YearJoined":1999
},
{
"FirstName":"FirstName7b08da9c-8c13-47f7-abe9-09b73b935e1f",
"LastName":"Next Last",
"YearJoined":1999
},
{
"FirstName":"FirstName836d4c54-b227-4c1b-b684-de4cd940c251",
"LastName":"last1",
"YearJoined":1999
},
{
"FirstName":"FirstName5f53e895-921e-4130-8ed8-610b017f3b9b",
"LastName":"last2",
"YearJoined":1999
},
{
"FirstName":"FirstName9cf6b05f-38aa-47c1-9fd7-e3c1009cf3e4",
"LastName":"Last Last",
"YearJoined":1999
}
]
If you use the list builder functionality and get the following error:
Castle.DynamicProxy.Generators.GeneratorException: Can not create proxy for type <YOUR_BUILDER_CLASS> because it is not accessible. Make it public, or internal and mark your assembly with [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] attribute, because assembly <YOUR_TEST_ASSEMBLY> is not strong-named.
Then you either need to:
- Make your builder class public
- Add the following to your
AssemblyInfo.csfile:[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
If you use the list builder functionality and get the following error:
System.InvalidOperationException: Tried to build a list with a builder who has non-virtual method. Please make <METHOD_NAME> on type <YOUR_BUILDER_CLASS> virtual.
Then you need to mark all the public methods on your builder as virtual. This is because we are using Castle Dynamic Proxy to generate lists and it can't intercept non-virtual methods.
In the previous examples, you have seen how to create entities explicitly, by calling the Build() and BuildList() methods. For the ultimate in terseness, you can omit these methods, and Dossier will implicitly call them for you. The one caveat is that you must explicitly declare the variable type rather than using the var keyword (unless you are passing into a method with the desired type).
So, to create a single entity:
Customer customer = new CustomerBuilder();
Customer customer = new CustomerBuilder()
.WithFirstName("Matt")
.WithLastName("Kocaj")
.WhoJoinedIn(2010);
Or to create a list of entities:
List<Customer> entities = CustomerBuilder.CreateListOfSize(5);
List<Customer> data = CustomerBuilder.CreateListOfSize(3)
.TheFirst(1).WithFirstName("John");
If you are building domain entities, or other important classes, having a custom builder class with intention-revealing method (e.g. WithFirstName) provides terseness (avoiding lambda expressions) and allows the builder class to start forming documentation about the usage of that object.
Sometimes though, you just want to build a class without that ceremony. Typically, we find that this applies for view models and DTOs.
In that instance you can use the generic Builder implementation as shown below:
StudentViewModel vm = Builder<StudentViewModel>.CreateNew()
.Set(x => x.FirstName, "Pi")
.Set(x => x.LastName, "Lanningham")
.Set(x => x.EnrollmentDate, new DateTime(2000, 1, 1));
var studentViewModels = Builder<StudentViewModel>.CreateListOfSize(5)
.TheFirst(1).Set(x => x.FirstName, "First")
.TheNext(1).Set(x => x.LastName, "Next Last")
.TheLast(1).Set(x => x.LastName, "Last Last")
.ThePrevious(2).With(b => b.Set(x => x.LastName, "last" + (++i).ToString()))
.All().Set(x => x.EnrollmentDate, _enrollmentDate)
.BuildList();
The syntax is modelled closely against what NBuilder provides and the behaviour of the class should be very similar.
Note, that in the first example above, it was not necessary to call the Build method at the end of the method chain. This is because the vm variable has been defined as StudentViewModel and the C# compiler is able to infer the type and the object is set implicitly.
In the second example, the var keyword is used to define studentViewModels, and so it is necessary to explicitly call BuildList to set the variable.
By default, the longest constructor of the class you specify will be called and then all properties (with public and private setters) will be set with values you specified (or anonymous values if none were specified).
Sometimes you might not want this behaviour, in which case you can specify a custom construction factory (see Build objects without calling constructor section for explanation of factories) as shown below:
var dto = Builder<MixedAccessibilityDto>
.CreateNew(new CallConstructorFactory())
.Build();
var dtos = MixedAccessibilityDto dto = Builder<MixedAccessibilityDto>
.CreateListOfSize(5, new CallConstructorFactory())
.BuildList();
When you extend the TestDataBuilder as part of creating a custom builder you will be forced to override the abstract BuildObject method. You have full flexibility to call the constructor of your class directly as shown above, but you can also invoke some convention-based factories to speed up the creation of your builder (also shown above) using the BuildUsing method.
The BuildUsing method takes an instance of IFactory, of which you can create your own factory implementation that takes into account your own conventions or you can use one of the built-in ones:
AllPropertiesFactory- Calls the longest constructor with builder values (or anonymous values if none set) based on case-insensitive match of constructor parameter names against property names and then calls the setter on all properties (public or private) with builder values (or anonymous values if none set)PublicPropertySettersFactory- Calls the longest constructor with builder values (or anonymous values if none set) based on case-insensitive match of constructor parameter names against property names and then calls the setter on all properties with public setters with builder values (or anonymous values if none set)CallConstructorFactory- Calls the longest constructor with builder values (or anonymous values if none set) based on case-insensitive match of constructor parameter names against property namesAutoFixtureFactory- Asks AutoFixture to create an anonymous instance of the class (note: does not use any builder values or anonymous values from Dossier)
Within a particular instance of AnonymousValueFixture, which is created for every builder, any generators that return a sequence of values (e.g. unique values) will be maintained. If you want to ensure that the same anonymous value fixture is used across multiple related builders then:
-
Using
CreateListOfSizewill automatically propagate the anonymous value fixture across builders -
Call the
GetChildBuilder<TChildObject, TChildBuilder>(Func<TChildBuilder, TChildBuilder> modifier = null)method from within your custom builder, e.g.:public MyCustomBuilder WithSomeValue(Func<SomeBuilder, SomeBuilder> modifier = null) { return Set(x => x.SomeValue, GetChildBuilder<SomeObject, SomeBuilder>(modifier)); } -
If using
Builder<T>then call theSetUsingBuildermethod, e.g.:// Uses Builder<T> Builder<StudentViewModel>.CreateNew() .SetUsingBuilder(x => x.Address) .Build() // Uses Builder<T>, includes customisation Builder<StudentViewModel>.CreateNew() .SetUsingBuilder(x => x.Address, b => b.Set(y => y.Street, "A street")) .Build() // Uses AddressBuilder Builder<StudentViewModel>.CreateNew() .SetUsingBuilder<AddressViewModel, AddressViewModelBuilder>(x => x.Address) .Build() // Uses AddressBuilder, includes customisation Builder<StudentViewModel>.CreateNew() .SetUsingBuilder<AddressViewModel, AddressViewModelBuilder>(x => x.Address, b => b.Set(y => y.Street, "A street")) .Build()
There is currently no way to share an anonymous value fixture across unrelated builder instances. If this is something you need please raise an issue so we can discuss your requirement.
todo: Coming soon!
This library integrates with NSubstitute for generating proxy objects, this means you can call the AsProxy method on your builder to request that the result from calling Build will be an NSubstitute proxy with the public properties set to return the values you have specified via your builder, e.g.
var customer = CustomerBuilder.WithFirstName("Rob").AsProxy().Build();
customer.CustomerForHowManyYears(Arg.Any<DateTime>()).Returns(10);
var name = customer.FirstName; // "Rob"
var years = customer.CustomerForHowManyYears(DateTime.Now); // 10
If you need to alter the proxy before calling Build to add complex behaviours that can't be expressed by the default public properties returns values then you can override the AlterProxy method in your builder, e.g.
class CustomerBuilder : TestDataBuilder<Customer, CustomerBuilder>
{
// ...
private int _years;
public CustomerBuilder HasBeenMemberForYears(int years)
{
_years = years;
return this;
}
protected override void AlterProxy(Customer proxy)
{
proxy.CustomerForHowManyYears(Arg.Any<DateTime>()).Returns(_years);
}
// ...
}
// Then in your test you can use:
var customer = new CustomerBuilder().AsProxy().HasBeenMemberForYears(10);
var years = customer.CustomerForHowManyYears(DateTime.Now); // 10
Remember that when using proxy objects of real classes that you need to mark properties and methods as virtual and have a protected empty constructor.
TestStack.Dossier is an opinionated framework and as such prescribes how to build your fixture data, including how to build lists, anonymous data and mock objects. Because of this we have decided to bundle it with the best of breed libraries for this purpose: AutoFixture and NSubstitute.
This allows for this library to provide a rich value-add on top of the basics of tracking properties in a dictionary in the TestDataBuilder base class. If you want to use different libraries or want a cut down version that doesn't come with NSubstitute or AutoFixture and the extra functionality they bring then take the TestDataBuilder.cs file and cut out the bits you don't want - open source ftw :).
If you have a suggestion for the library that can incorporate this value-add without bundling these libraries feel free to submit a pull request.
If you would like to contribute to this project then feel free to communicate with Rob via Twitter (@robdmoore) or alternatively submit a pull request / issue.