问题
I have xUnit/Moq/AutoFixture successfully working together so that I am auto mocking objects via test method input parameters. I created a custom [AutoMoqData]
attribute which I use on every test. Here's the code for the attribute:
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());
}
}
}
This works, but I get the following compile warning: 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.'
I've muted the warning by surrounding it with a #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
}
}
}
However, I want to set this up correctly and not have to pretend like the warning doesn't exist. The problem is, I'm having trouble figuring out the correct syntax for the two lines inside of the #pragma
.
Any ideas?
回答1:
Just use a lambda with body to additionally configure the fixture
instance before returning it:
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;
})
{
}
}
This way the Fixture
activation will be truly lazy and you will get the expected performance optimization ;-)
来源:https://stackoverflow.com/questions/54261179/when-setting-up-a-custom-autodataattribute-for-auto-mocking-whats-the-proper-s