AutoFixture:如何从System.Type创建匿名 [英] AutoFixture: how to CreateAnonymous from a System.Type

查看:100
本文介绍了AutoFixture:如何从System.Type创建匿名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要使用System.Type从AutoFixture创建对象.但是,似乎没有CreateAnonymous()的重载只是接受一个类型.他们都希望使用编译时通用的T.是否可以将System.Type转换为T?

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:

我正在使用AutoMapper,它具有一个用于注入组件的钩子以支持复杂的映射方案:

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

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

从签名中可以看到,

客户端可以注册Func,AutoMapper可以在需要注入服务的任何时间调用该Func(主要是ValueResolver实现).

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

在生产版本中,此方法调用我的StructureMap容器​​以检索组件.但是,在对映射代码进行单元测试时,我必须提供存根实现,否则AutoMapper会引发异常.由于我将AutoFixture + Moq用作自动模拟容器,因此让AF填充完全水合的存根似乎很自然,因此我可以专注于编写单元测试代码.

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);

在AutoFixture中,有很多可扩展性点,它们通常比弱类型的Create方法提供更好的选择.您想完成什么?

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?

这篇关于AutoFixture:如何从System.Type创建匿名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆