4

这是我正在尝试做的事情:

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传递给测试的参数每个都有UserId1 但这不是发生的情况。

我怎样才能做到这一点?

4

1 回答 1

4

您可以通过创建自定义AutoData属性派生类型来做到这一点:

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));
        }
    }
}

您还可以添加其他自定义项。请记住,顺序很重要


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

public class MyTests
{
    [Theory, MyAutoData]
    public void GetThingsByUserId_ShouldReturnThings(IEnumerable<Thing> things)
    {
        things.First().UserId.Should().Be(1);
    }
}
于 2015-06-30T11:24:10.083 回答