In my previous post I described how to customize a Fixture instance to populate lists with items instead of returning empty lists. While it's pretty easy to do so, the drawback is that you have to do it explicitly for every type you want to influence. In this post I will follow up by describing how to enable some general conventions that simply populates all collections that the Fixture resolves.

This post describes a feature that will be available in AutoFixture 2.1. It's not available in AutoFixture 2.0, but is already available in the code repository. Thus, if you can't wait for AutoFixture 2.1 you can download the source and built it.

Instead of having to create multiple customizations for IEnumerable<int>, IList<int>, List<int>, IEnumerable<string>, IList<string>, etc. you can simply enable these general conventions as easy as this:

var fixture = new Fixture()
    .Customize(new MultipleCustomization());

Notice that enabling conventions for populating sequences and lists with ‘many' items is an optional customization that you must explicitly add.

This feature must be explicitly enabled. There are several reasons for that:

  • It would be a breaking change if AutoFixture suddenly started to behave like this by default.
  • The MultipleCustomization targets not only concrete types such as List<T> and Collection<T>, but also interfaces such as IEnumerable<T>, IList<T> etc. Thus, if you also use AutoFixture as an Auto-Mocking container, I wanted to provide the ability to define which customization takes precedence.

With that simple customization enabled, all requested IEnumerable<T> are now populated. The following will give us a finite, but populated list of integers:

var integers = 
    fixture.CreateAnonymous<IEnumerable<int>>();

This will give us a populated List<int>:

var list = fixture.CreateAnonymous<List<int>>();

This will give us a populated Collection<int>:

var collection = 
    fixture.CreateAnonymous<Collection<int>>();

As implied above, it also handles common list interfaces, so this gives us a populated IList<T>:

var list = fixture.CreateAnonymous<IList<int>>();

The exact number of ‘many' is as always determined by the Fixture's RepeatCount.

As this code is still (at the time of publishing) in preview, I would love to get feedback on this feature.



Wish to comment?

You can add a comment to this post by sending me a pull request. Alternatively, you can discuss this post on Twitter or Google Plus, or somewhere else with a permalink. Ping me with the link, and I may add it as a comment.

Published

Tuesday, 08 February 2011 14:53:16 UTC

Tags



"Our team wholeheartedly endorses Mark. His expert service provides tremendous value."
Hire me!