2

我正在尝试将共享部件创建策略用于 MEF 导出。然而,它似乎不像我想的那样工作。我在我的应用程序中做了两次合成,每次都得到一个新的对象副本。我已经通过向对象实例化添加实例计数器来证明这一点

    static int instCount = 0;

    public FakeAutocompleteRepository()
    {
        instCount++;
        ...
    }

并在调试中运行它。事实上,我第二次进行组合时,我得到了一个新的 FakeAutocompleteRepository 副本,其中 instCount = 2。导出部分包含

[PartCreationPolicy(CreationPolicy.Shared)]
[Export(typeof(IAutocompleteRepository))]
[ExportMetadata("IsTesting", "True")]
class FakeAutocompleteRepository : IAutocompleteRepository
{ ... }

是否有一些技巧可以为后续请求获取相同的实例?如果这是我在作曲期间正在做的事情,我就是这样做的

var catalog = new AggregateCatalog();
                catalog.Catalogs.Add(new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly()));
                catalog.Catalogs.Add(new DirectoryCatalog("."));
                var container = new CompositionContainer(catalog);
                var batch = new CompositionBatch();
                batch.AddPart(this);
                container.Compose(batch);


                if (null != ConfigurationSettings.AppSettings["IsTesting"] && bool.Parse(ConfigurationSettings.AppSettings["IsTesting"]))
                    repository = container.GetExports<IAutocompleteRepository>().Where(expDef => expDef.Metadata.Keys.Contains("IsTesting")).Single().GetExportedObject();

基本上我试图在测试期间强制使用特定的组合。如果您对这些作品的单元测试有更好的想法,那么我会全力以赴。

4

2 回答 2

3

我没有在您的代码中看到任何会导致您创建多个部分的具体内容。您是否为每个组合创建不同的容器?如果你是,这就是你得到单独实例的原因。

至于如何结合组合测试和单元测试,这里有一些讨论

于 2009-05-05T05:39:31.307 回答
2

我为单元测试所做的是避免组合。例如(我在这里使用 WPF 和 MVVM),假设你想测试这个 ViewModel:

[Export("/MyViewModel")]
public class MyViewModel
{
    [ImportingConstructor]
    public MyViewModel(
        [Import("/Services/LoggingService")] ILoggingService l)
    {
        logger = l;
    }

    private ILoggingService logger { get; set; }

    /* ... */
}

我不想在每次进行单元测试时都实例化完整的日志记录服务,所以我有一个实现 ILoggingService 的 MockLoggingService 类,它只会吞下所有日志消息,(或检查是否正在生成正确的消息,如果你在意)。然后我可以在我的单元测试中这样做:

MyViewModel target = new MyViewModel(new MockLoggingService());
于 2009-05-15T01:22:21.033 回答