我可以在XUnit构造函数中自定义Fixture以与Theory和AutoData一起使用吗?

时间:2015-06-30 10:39:29

标签: c# .net xunit autofixture xunit2

以下是我要做的事情:

public class MyTests
{
    private IFixture _fixture;

    public MyTests()
    {
        _fixture = new Fixture();
        _fixture.Customize<Thing>(x => x.With(y => y.UserId, 1));
    }

    [Theory, AutoData]
    public void GetThingsByUserId_ShouldReturnThings(IEnumerable<Thing> things)
    {
        things.First().UserId.Should().Be(1);
    }
}

我希望传入测试的IEnumerable<Thing> things参数每个都有UserId为1,但这不会发生。

我该如何做到这一点?

1 个答案:

答案 0 :(得分:3)

您可以通过创建自定义AutoData属性derived-type:

来实现
internal class MyAutoDataAttribute : AutoDataAttribute
{
    internal MyAutoDataAttribute()
        : base(
            new Fixture().Customize(
                new CompositeCustomization(
                    new MyCustomization())))
    {
    }

    private class MyCustomization : ICustomization
    {
        public void Customize(IFixture fixture)
        {
            fixture.Customize<Thing>(x => x.With(y => y.UserId, 1));
        }
    }
}

您还可以添加其他自定义项。请记住the order matters

然后,将测试方法更改为使用MyAutoData属性,如下所示:

public class MyTests
{
    [Theory, MyAutoData]
    public void GetThingsByUserId_ShouldReturnThings(IEnumerable<Thing> things)
    {
        things.First().UserId.Should().Be(1);
    }
}
相关问题