문제

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.

도움이 되었습니까?

해결책

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?

다른 팁

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?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top