![](/img/trans.png)
[英]How to fulfill System.Composition MEF ImportingConstructor with an instance
[英]How to mock dependencies for a WebApi 2 controller when using MEF 2 (System.Composition)?
使用MEF(System.ComponentModel.Composition),可以将模拟对象添加到容器中。
container.ComposeExportedValue(mock.Object);
参考: 如何使用Moq满足MEF导入依赖关系以进行单元测试?
使用便携式MEF库(System.Composition)怎么可能?
有关更多上下文,我将发布到目前为止的一堆代码。
我正在通过内存ASP.NET Web API创建xBehave.net集成测试。
我因此建立了客户。
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) { }
这是测试。 模拟是使用Moq创建的。
[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容器吗?
您可以使用MEF CodePlex站点的Microsoft.Composition.Demos.ExtendedPartTypes
示例中采用的方法来执行此操作。 下面显示了为IAmMocked
服务注册实例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
我们打算在某个时候把它“装进盒子里”,但我不相信它发生了。 如果您在运行时遇到任何问题,请告诉我!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.