Autofixture Constructer注入延迟加载

时间:2013-08-19 06:54:06

标签: c# unit-testing autofixture

我在单元测试中使用自动混合,它作为自动锁定器的方式非常棒。

但是在将延迟加载的对象注入我的类时遇到问题。例如:

public class MyClass : IMyClass
{
    private Lazy<IMyInjectedClass> _myInjectedClassLazy;
    private IMyInjectedClass _myInjectedClass {
        get { return _myInjectedClassLazy.Value; }
    }

    public MyClass(Lazy<IMyInjectedClass> injectedClass)
    {
        _myInjectedClassLazy = _myInjectedClass;
    }

    public void DoSomething()
    {
        _myInjectedClass.DoSomething();
    }
}

然后当我尝试运行测试时,我使用autofixture来生成类:

public class MyTests
{
    [Test]
    public void ShouldDoSomething()
    {
        var fixture = new Fixture().Customize(new AutoMoqCustomization());
        fixture.Behaviors.Remove(new ThrowingRecursionBehavior());
        fixture.Behaviors.Add(new OmitOnRecursionBehavior());

        var mockMyClass = fixture.Freeze<Mock<IMyClass>>();

        var sut = fixture.Create<MyClass>();

        sut.DoSomething();
    }
}

但是这段代码会抛出以下错误:

  

System.MissingMemberException:lazily-initialized类型没有公共的无参数构造函数。

使用自动混合时,有没有办法可以避免此错误并注入惰性对象?

1 个答案:

答案 0 :(得分:1)

FWIW,虽然我不同意这样做的动机,但您可以告诉AutoFixture如何创建Lazy<IMyInjectedClass>的实例:

var fixture = new Fixture().Customize(new AutoMoqCustomization());
fixture.Behaviors.Remove(new ThrowingRecursionBehavior());
fixture.Behaviors.Add(new OmitOnRecursionBehavior());
fixture.Register(                                                   // Add this 
    (IMyInjectedClass x) => new Lazy<IMyInjectedClass>(() => x));   // to pass

var mockMyClass = fixture.Freeze<Mock<IMyClass>>();

var sut = fixture.Create<MyClass>();

sut.DoSomething();

如果您需要反复执行此操作,则应考虑packaging this in a Customization