AutoFixture > Customize objects creation with ICustomization interface

In this post we will look at AutoFixture basic customization features starting with ICustomization interface.

We will use following DateRange class as demonstration example.

    public class DateRange
        public DateTime Start { get; private set; }
        public DateTime Finish { get; private set; }

        public DateRange(DateTime start, DateTime finish)
            if (start > finish)
                throw new ArgumentException("Finish date must be less than or equal to Start date");

            Start = start;
            Finish = finish;

If we write test method using DateRange as parameter:

using Ploeh.AutoFixture;
using Ploeh.AutoFixture.Xunit2;
using Xunit;

public class DateRangeTests
        [Theory, AutoData]
        public void ShowCaseTest(DateRange sut)
            //skip the body to focus at the DateRange object creation

Test will sometimes fail with “System.ArgumentExceptionFinish date must be less than or equal to Start date”. Because by default AutoFixture library will just pass two random DateTime as constructor parameter and the validation logic inside constructor is not considered.

Let’s fix it by implementing ICustomization interface to create valid DateRange object.

 public class CustomAutoDataAttribute : AutoDataAttribute
        public CustomAutoDataAttribute()
            : base(new Fixture()
            .Customize(new ValidDateRangeCustomization()))
        { }

    public class ValidDateRangeCustomization : ICustomization
        public void Customize(IFixture fixture)
            fixture.Register(() =>
                var start = fixture.Create<DateTime>();
                return new DateRange(start, start.AddDays(1));

The last step is to to use CustomAutoData in the test instead of default AutoData.

    [Theory, CustomAutoData]
    public void DoSomeTest(DateRange sut)

This entry was posted in programming, Unit test and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s