Introduction

AutoFixture, if you’ve not heard of it, allows for generation of anonymous data in unit tests. This allows for generating random numbers, strings etc. as well as more complex object graphs to allow you, the developer, to concentrate on the testing and not the creation of the test data.

With the release of C# 9 recently and the new record types I was curious to see if AutoFixture could handle them.

Let’s see!

Walkthrough

Let’s start off with the definition of the record type we are going to be using in these examples.

public record ProductId(int Value);

It’s relatively straight forward to test the basic setup.

Setting up usage of a record type is really straight forward and on first viewing you might be mistaken it’s a class from it’s construction.

[Fact]
public void ByItSelf()
{
    var product = new ProductId(11);
}

This will create a new ProductId record with the value of 11. Pretty straight forward.

When you generate data using AutoFixture the starting point is always the Fixture class.

[Fact]
public void With_Fixture()
{
    var fixture = new Fixture();

    var product = fixture.Create<ProductId>();
}

Like creating an instance of a POCO class requesting a new ProductId to be created is exactly the same. Debugging through this test you will be able to see that the int value provided to the constructor is randomly seeded as you’d expect.

But can it work with the xUnit data attributes?

Of course it can!

You can decorate any test which is marked with the [Theory] attribute with the [AutoData] extension attribute and specify the parameter being passed into the test method is of our record type. Under the hood this will do exactly what we did in the previous example but the Fixture instance is managed by the extension library.

[Theory]
[AutoData]
public void With_Attribute(ProductId productId)
{

}

The above will inject an instance of ProductId with a randomly seeded int as before but without you having to write the Fixture code.

If you’ve not seen it before AutoDataAttribute is part of the AutoFixture.Xunit2 nuget package which I highly recommand you check out.

Conclusion

In short Autofixture can handle the new record type no problem. I’ve only tried it on simple samples but it appears to be able to handle it like other types and generates the required anonymous values as expected.

Done some crazy stuff with record types and AutoFixture? Managed to break it? Please let me know on Twitter @WestDiscGolf.