Autofixture: Add non-generic Create(Type) method

Created on 19 Nov 2015  ·  2Comments  ·  Source: AutoFixture/AutoFixture

I (ab)use Autofixture to generate documentation examples for a Web API. The messages (commands and queries) that Autofixture will create for me are serialized to JSON and become part of the documentation. This works really really well, and it takes a few lines of code, compared to the hundreds of lines of ugly code that the VS template for Web API generates in its /HelpPage area (yuck).

Currently I use the following code to achieve this:

``` c#
private static readonly MethodInfo CreateMethodInfo =
GetMethod(() => SpecimenFactory.Create(new Fixture()))
.GetGenericMethodDefinition();

public static object Create(Type type)
{
var fixture = new Fixture();
int index = 1;
fixture.Register(() => "sample text " + index++);

return CreateMethodInfo.MakeGenericMethod(type).Invoke(null, new object[] { fixture });

}

private static MethodInfo GetMethod(Expression> methodCall) =>
((MethodCallExpression)methodCall.Body).Method;
```

Since I don't know the exact message at compile time, I can't call Autofixture's Fixture.Create<T>() method. As the above code shows, the way I currently solved this is by invoking this generic Create<T> method using reflection.

Is there a simpler way to do achieve my goal, and if not, could a non-generic Create(Type) method be added to the library?

Most helpful comment

Would this solution work?

c# var specimen = new SpecimenContext(fixture).Resolve(type);

All 2 comments

Would this solution work?

c# var specimen = new SpecimenContext(fixture).Resolve(type);

Cool! That does the trick! Thanks.

Was this page helpful?
0 / 5 - 0 ratings