使用MEF (System.ComponentModel.Composition),可以向容器中添加模拟对象。
container.ComposeExportedValue(mock.Object);参考文献:https://stackoverflow.com/a/10223318/444244
如何使用可移植的MEF库(System.Composition)?
为了获得更多的上下文,我将发布一堆我到目前为止得到的代码。
我正在内存中的xBehave.net ASP.NET网络API上创建ASP.NET网络API集成测试。
我就这样安排了客户。
config = new HttpConfiguration();
WebApiConfig.Register(config);
config.DependencyResolver = MefConfig();
server = new HttpServer(config);
Client = new HttpClient(server);
Request = new HttpRequestMessage();我设置了MEF配置,就像WebApiContrib.IoC.Mef的默认配置一样。
private static IDependencyResolver MefConfig()
{
var conventions = new ConventionBuilder();
conventions.ForTypesDerivedFrom<IHttpController>().Export();
conventions.ForTypesMatching(
t => t.Namespace != null && t.Namespace.EndsWith(".Parts"))
.Export()
.ExportInterfaces();
var container = new ContainerConfiguration()
.WithAssemblies(
new[] { Assembly.GetAssembly(typeof(ICache)) }, conventions)
.CreateContainer();
return new MefDependencyResolver(container);
}这是我想测试的控制器的签名。它从缓存中读取。
public MyController(ICache cache) { }这是测试。模拟是用莫克创建的。
[Scenario]
public void RetrieveOnPollingRequest()
{
const string Tag = "\"tag\"";
string serverETag = ETag.Create(Tag);
"Given an If-None-Match header"
.f(() => Request.Headers.IfNoneMatch.Add(
new EntityTagHeaderValue(Tag)));
"And the job has not yet completed"
.f(() =>
{
string tag = serverETag;
this.MockCache.Setup(x => x.StringGet(tag)).Returns(Tag);
});
"When retrieving jobs"
.f(() =>
{
Request.RequestUri = uri;
Response = Client.SendAsync(Request).Result;
});
"Then the status is Not-Modified"
.f(() =>
Response.StatusCode.ShouldEqual(HttpStatusCode.NotModified));
}那么,如何将模拟输入容器,而不是已经导出的部件?或者我不是吗?我需要去使用不同的IoC容器吗?
发布于 2014-09-06 11:35:48
您可以使用Microsoft.Composition.Demos.ExtendedPartTypes示例中从MEF站点采取的方法来完成这一操作。下面显示了为mockObject服务注册实例IAmMocked:
var container = new ContainerConfiguration()
.WithExport<IAmMocked>(mockObject)
.WithAssemblies(
new[] { Assembly.GetAssembly(typeof(ICache)) }, conventions)
.CreateContainer();您将在这里找到完整的代码:http://mef.codeplex.com/SourceControl/latest#oob/demo/Microsoft.Composition.Demos.ExtendedPartTypes/Program.cs
我们打算在某个时候把这件事“放进盒子里”,但我不相信它已经发生了。如果你有任何困难让它运行,请告诉我!
https://stackoverflow.com/questions/25669720
复制相似问题