C# 测试依赖MEF注入的非导出类

C# 测试依赖MEF注入的非导出类,c#,silverlight,prism,mef,C#,Silverlight,Prism,Mef,我使用MEF将对象组合在一起,在测试某些类时遇到了问题,这些类没有导出到MEF容器,而是依赖MEF将对象实例注入属性设置器 例如考虑以下两种视图模型 public class ViewModelA { [Import] internal IAdmin AdminService { get; private set; } public ViewModelA() { CompositionInitial

我使用MEF将对象组合在一起,在测试某些类时遇到了问题,这些类没有导出到MEF容器,而是依赖MEF将对象实例注入属性设置器

例如考虑以下两种视图模型

public class ViewModelA
{
    [Import]
    internal IAdmin AdminService
    {
        get;
        private set;
    }

    public ViewModelA()
    {
        CompositionInitializer.SatisfyImports(this);
    }

    //constructor for testing
    internal ViewModelA(IAdmin adminService)
    {
        this.AdminService = adminService;
    }

    public void DoSomething()
    {
        this.AdminService.SetCurrentWindow(new ViewModelB());
    }
}


public class ViewModelB 
{
    [Import]
    internal IAdmin AdminService
    {
        get;
        private set;
    }

    [Import]
    internal IAnotherService AnotherServiceService
    {
        get;
        private set;
    }

    public ViewModelB()
    {
        CompositionInitializer.SatisfyImports(this);
    }

    public void DoAnotherThing()
    {
        //Does something with the properties injected via MEF
    }

}
这些类不会导出到MEF容器,因此我依赖于调用
CompositionInitializer.satisfyiImports(this)
强制导入依赖项

我想为ViewModelA创建一个测试,检查调用DoSomething后,
IAdmin.SetCurrentWindow
方法被ViewModelB实例调用一次。为了满足这一点,我为ViewModelA创建了一个构造函数重载,它将IAdmin作为参数,我还使用Moq和Silverlight单元测试框架创建了以下测试

    [TestMethod]
    public void DoSomethingStandard_CallsSetCurrentWindowWithViewModelB()
    {
        var adminServiceMock = new Mock<IAdmin>();
        var vmA = new ViewModelA(adminServiceMock.Object);
        vmA.DoSomething();
        adminServiceMock.Verify(ad => ad.SetCurrentWindow(It.IsAny<ViewModelB>()), Times.Exactly((1)));
    }
[TestMethod]
public void dosomething标准_调用ViewModelB()的当前窗口
{
var adminServiceMock=new Mock();
var vmA=newviewmodela(adminServiceMock.Object);
vmA.DoSomething();
adminServiceMock.Verify(ad=>ad.SetCurrentWindow(It.IsAny()),Times.justice((1));
}
我的问题是,当测试运行对
ViewModelA.DoSomething
的调用时,会实例化一个ViewModelB,而该ViewModelB又会抛出一个

System.Reflection.ReflectionTypeLoadException:无法加载一个或多个请求的类型。有关详细信息,请检索LoaderExceptions属性

这是因为ViewModelB构造函数调用了CompositionInitializer.satisfyiImports(This),但在我的测试项目中没有设置MEF容器


对于如何最好地测试这样一个场景,有什么想法吗?或者如何重新构造代码以使其可测试?

我认为您唯一能做的就是使用公共setter将[Import]ed属性更改为公共属性,并直接设置实例。您不应该在单元测试中担心MEF

这会更深入一点