AutoFixture was originally build as a tool for Test-Driven Development (TDD), and TDD is all about feedback. In the spirit of GOOS, you should listen to your tests. If the tests are hard to write, you should consider your API design. AutoFixture tends to amplify that sort of feedback.
Frankly, immutable types are a pain in C#, but you can make it easier to work with a class like Rsvp
if you take a cue from F# and introduce copy and update semantics. If you modify Rsvp
like this, it's going to be much easier to work with overall, and thus, as a by-product, also to unit test:
public class Rsvp
{
public string Response { get; private set; }
public DateTime CreatedDate { get; private set; }
public Rsvp(string response, DateTime createdDate)
{
Response = response;
CreatedDate = createdDate;
}
public Rsvp WithResponse(string newResponse)
{
return new Rsvp(newResponse, this.CreatedDate);
}
public Rsvp WithCreatedDate(DateTime newCreatedDate)
{
return new Rsvp(this.Response, newCreatedDate);
}
}
Notice that I've add two WithXyz
methods, that return a new instance with that one value changed, but all other values held constant.
This would enable you to create an instance of Rsvp
for testing purposed like this:
var fixture = new Fixture();
var seed = fixture.Create<Rsvp>();
var sut = seed.WithResponse("Attending");
or, as a one-liner:
var sut = new Fixture().Create<Rsvp>().WithResponse("Attending");
If you can't change Rsvp
, you can add the WithXyz
methods as extension methods.
Once you've done this about a dozen times, you get tired of it, and it's time to make the move to F#, where all that (and more) is built-in:
type Rsvp = {
Response : string
CreatedDate : DateTime }
You can create an Rsvp
record with AutoFixture like this:
let fixture = Fixture()
let seed = fixture.Create<Rsvp>()
let sut = { seed with Response = "Attending" }
or, as a one-liner:
let sut = { Fixture().Create<Rsvp>() with Response = "Attending" }
Build<T>().FromFactory(Func<T> factory)
throws InvalidCastException when I try it. Does this still work in AutoFixture 4.0? – Toadinthehole