本文介绍了我怎么能告诉AutoFixture总是创建TDerived当实例化一个TBASE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个深度嵌套的对象模型,其中一些类可能看起来有点像这样:

I have a deeply-nested object model, where some classes might look a bit like this:

class TBase { ... }

class TDerived : TBase { ... }

class Container
{
    ICollection<TBase> instances;
    ...
}

class TopLevel
{
    Container container1;
    Container container2;
    ...
}



我想创建我的顶级级别对象作为测试夹具,但我希望所有的 TBASE 情况下(如在情况下,上述集合),以为 TDerived 的实例,而不是 TBASE

I'd like to create my top-level object as a test fixture, but I want all the TBase instances (such as in the instances collection above) to be instances of TDerived rather than TBase.

我想我可以做到这一点很简单使用类似:

I thought I could do this quite simply using something like:

var fixture = new Fixture();

fixture.Customize<TBase>(c => c.Create<TDerived>());

var model = this.fixture.Create<TopLevel>();



...但是,这并不工作,因为在 lambda表达式自是错误的。我猜有办法做到这一点,但AutoFixture似乎缺少文件,不是作为一个流的意识对开发者的博客等。

...but that doesn't work, because the lambda expression in Customize is wrong. I'm guessing there's a way to do this, but AutoFixture seems to lack documentation, other than as a stream-of-consciousness on the developer's blog.

任何人都可以点我朝着正确的方向吗?

Can anyone point me in the right direction?

推荐答案

虽然由dcastro答案也是一种选择,最安全的办法是使用类。

While the answer by dcastro is also an option, the safest option is to use the TypeRelay class.

fixture.Customizations.Add(
    new TypeRelay(
        typeof(TBase),
        typeof(TDerived));

这篇关于我怎么能告诉AutoFixture总是创建TDerived当实例化一个TBASE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 16:44