Creating proxy objects
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.
Updated less than a minute ago