Question

I'm creating an AutoFixture specimen builder for a particular type, in this case System.Data.DataSet. The builder will return a FakeDataSet, which is a customized DataSet for testing.

The following doesn't work, with dataSet always returning null, even when a DataSet is being requested (I can tell by drilling into the request properties).

public class DataSetBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        var dataSet = request as DataSet;
        if (dataSet == null)
        {
            return new NoSpecimen(request);
        }

        return new FakeDataSet();
    }
}

This variation does work, but seems overly complex. It feels like there is a better way to accomplish the same thing, and I'm just missing something.

public class DataSetBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        var seededRequest = request as SeededRequest;
        if (seededRequest == null)
        {
            return new NoSpecimen(request);
        }

        var requestType = seededRequest.Request as Type;
        if (requestType == null)
        {
            return new NoSpecimen(request);
        }

        if (requestType.Name != "DataSet")
        {
            return new NoSpecimen(request);
        }

        return new FakeDataSet();
    }
}
Was it helpful?

Solution

It would be simpler to do this:

fixture.Register<DataSet>(() => new FakeDataSet());

but if you want to use a SpecimenBuilder, this should also work:

public class DataSetBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        var t = request as Type;
        if (typeof(DataSet).Equals(t))
            return new FakeDataSet();

        return new NoSpecimen(request);
    }
}

Personally, I'd use the first option.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top