Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoFixture: how to CreateAnonymous from a System.Type

I need to create an object from AutoFixture using nothing more than a System.Type. However, there doesn't appear to be an overload of CreateAnonymous() that simply takes a type. They all expect a compile time generic T. Is there a way to convert a System.Type to T?

Edit with usage details:

I'm using AutoMapper, which has a hook for injecting components to support complex mapping scenarios:

void ConstructServicesUsing(System.Func<Type,object> constructor)

As you can see from the signature, clients can register a Func which AutoMapper invokes anytime it needs an injected service (mostly ValueResolver implementations).

In production builds, this method calls into my StructureMap container to retrieve a component. However, when unit testing my mapping code, I must provide stub implementations otherwise AutoMapper throws an exception. Since I'm using AutoFixture + Moq as my automocking container, it seems natural to let AF new up a fully hydrated stub, so I can concentrate on writing unit test code.

like image 492
Mitch A Avatar asked May 14 '13 15:05

Mitch A


2 Answers

It's possible, but intentionally hidden, since you should very rarely need to do this:

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

There are tons of extensibility points in AutoFixture that, more often than not, provide a better alternative than a weakly typed Create method. What are you trying to accomplish?

like image 164
Mark Seemann Avatar answered Oct 21 '22 13:10

Mark Seemann


You have to use reflection to create the correct MethodInfo and call it. See this answer on how to do that: How to call generic method with a given Type object?

like image 42
Knaģis Avatar answered Oct 21 '22 13:10

Knaģis