为自动模拟设置自定义AutoDataAttribute时,告诉AutoFixture忽略所有递归结构的正确语法是什么?

时间:2019-01-18 20:42:35

标签: moq xunit autofixture automocking automoq

我成功地使xUnit / Moq / AutoFixture一起工作,以便通过测试方法输入参数自动模拟对象。我创建了一个自定义[AutoMoqData]属性,该属性将在每次测试中使用。这是该属性的代码:

using System.Linq;
using AutoFixture;
using AutoFixture.AutoMoq;
using AutoFixture.Xunit2;

namespace Shared.TestResources.AutoFixture
{
    public class AutoMoqDataAttribute : AutoDataAttribute
    {
        public AutoMoqDataAttribute() : base(() => new Fixture().Customize(new CompositeCustomization(new AutoMoqCustomization(), new SupportMutableValueTypesCustomization())))
        {
            this.Fixture.Behaviors.OfType<ThrowingRecursionBehavior>().ToList().ForEach(b => Fixture.Behaviors.Remove(b));
            this.Fixture.Behaviors.Add(new OmitOnRecursionBehavior());
        }
    }
}

这可行,但是我收到以下编译警告:warning CS0618: 'AutoDataAttribute.Fixture' is obsolete: 'Fixture is created lazily for the performance efficiency, so this property is deprecated as it activates the fixture immediately. If you need to customize the fixture, do that in the factory method passed to the constructor.'

我通过用#pragma包围警告来使其静音:

using System.Linq;
using AutoFixture;
using AutoFixture.AutoMoq;
using AutoFixture.Xunit2;

namespace Shared.TestResources.AutoFixture
{
    public class AutoMoqDataAttribute : AutoDataAttribute
    {
        public AutoMoqDataAttribute() : base(() => new Fixture().Customize(new CompositeCustomization(new AutoMoqCustomization(), new SupportMutableValueTypesCustomization())))
        {
#pragma warning disable 0618
            this.Fixture.Behaviors.OfType<ThrowingRecursionBehavior>().ToList().ForEach(b => Fixture.Behaviors.Remove(b));
            this.Fixture.Behaviors.Add(new OmitOnRecursionBehavior());
#pragma warning restore 0618
        }
    }
}

但是,我想正确地进行设置,而不必假装不存在警告。问题是,我在为#pragma内部的两行找出正确的语法时遇到了麻烦。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

只需使用带有body的lambda来额外配置fixture实例,然后返回它:

public class AutoMoqDataAttribute : AutoDataAttribute
{
    public AutoMoqDataAttribute() : base(() =>
    {
        var fixture = new Fixture().Customize(new CompositeCustomization(
            new AutoMoqCustomization(),
            new SupportMutableValueTypesCustomization()));

        fixture.Behaviors.OfType<ThrowingRecursionBehavior>().ToList().ForEach(b => Fixture.Behaviors.Remove(b));
        fixture.Behaviors.Add(new OmitOnRecursionBehavior());

        return fixture;
    })
    {
    }
}

通过这种方式Fixture的激活将是真正的延迟,您将获得预期的性能优化;-)