Mitch A
Mitch A

Reputation: 2118

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.

Upvotes: 23

Views: 4139

Answers (2)

Mark Seemann
Mark Seemann

Reputation: 233367

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?

Upvotes: 41

Knaģis
Knaģis

Reputation: 21495

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?

Upvotes: 1

Related Questions