8

I am using AutoFixture's [AutoData] attribute to provide some unit tests (NUnit) with an instance of a POCO. For example:

[Test, AutoData]
public void Create_NameIsNull_ThrowsException(MyPOCO myPOCO) {..}

I've recently added a new string property to my POCO that must always contain a properly formed URL.

Naturally, [AutoData] is not aware of this requirement and generates the usual GUID-based string value for this property. This causes my tests to fail (because of some Data Annotations based validation that I have in place).

I've followed @ploeh's advice and written a Convention-based Customization for AutoFixture that specifically generates a properly formatted URL string for this new property of mine. It is a class called UrlSpecimenBuilder that implements ISpecimenProvider.

My question is, how can I combine my new ISpecimenProvider with [AutoData]?

I don't want to have to go fixture.Customizations.Add(new UrlSpecimenBuilder()); in each one of my unit test. I'm looking for a single test fixture setup step that will do the same thing.

urig
  • 16,016
  • 26
  • 115
  • 184
  • 3
    As I also mentioned in our [Twitter conversation](https://twitter.com/urig/status/760085204971163649), the appropriate reaction would be to change the type of the property from `string` to `Uri`, thus avoiding [Primitive Obsession](http://blog.ploeh.dk/2011/05/25/DesignSmellPrimitiveObsession). In that conversation, you also hinted at this not being applicable in this case, but since that's not apparent to a casual reader of this post, I've added this comment. – Mark Seemann Aug 01 '16 at 21:58

2 Answers2

8

You should define your own version of the AutoDataAttribute and apply all the customizations you need. If the customizations are relevant for all the tests, it might be called DefaultAutoData:

[Test, DefaultAutoData]
public void Create_NameIsNull_ThrowsException(MyPOCO myPOCO) {..}

internal class DefaultAutoDataAttribute : AutoDataAttribute
{
  public DefaultAutoDataAttribute()
    : base(new Fixture().Customizations.Add(new UrlSpecimenBuilder()))
  {
  }
}

See this Mark Seemann post for details.

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
Serhii Shushliapin
  • 2,528
  • 2
  • 15
  • 32
4

You can also override the CustomizeAttribute to arrive at a syntax like

[Test, AutoData]
public void Create_NameIsNull_ThrowsException(
  [MyPOCOWithValidUrl] MyPOCO myPOCO) 
{..}

Some real world examples

Scotty.NET
  • 12,533
  • 4
  • 42
  • 51