简体   繁体   English

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

[英]Can I customise a Fixture in an XUnit constructor for use with Theory and AutoData?

Here is what I am trying to do: 这是我正在尝试做的事情:

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

I would expect the IEnumerable<Thing> things parameter passed into the test to each have a UserId of 1 but this is not what happens. 我希望传递给测试的IEnumerable<Thing> things参数具有一个UserId为1,但这不会发生。

How can I make this so? 我该怎么做呢?

You can do that by creating a custom AutoData attribute derived-type: 您可以通过创建自定义的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));
        }
    }
}

You may also add other Customizations. 您也可以添加其他自定义项。 Just keep in mind that the order matters . 请记住, 顺序很重要


Then, change the test method to use MyAutoData attribute instead, as shown below: 然后,将测试方法改为使用MyAutoData属性,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM