5

我让 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.

有任何想法吗?

4

1 回答 1

4

fixture只需在返回之前使用带有 body 的 lambda 来额外配置实例:

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激活将是真正的懒惰,您将获得预期的性能优化;-)

于 2019-01-26T20:44:00.990 回答