我可以在 XUnit 构造函数中自定义 Fixture 以与 Theory 和 AutoData 一起使用吗?
Can I customise a Fixture in an XUnit constructor for use with Theory and AutoData?
这是我正在尝试做的事情:
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,但事实并非如此。
我怎样才能做到这一点?
您可以通过创建自定义 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));
}
}
}
您还可以添加其他自定义项。请记住 the order matters.
然后,将测试方法更改为使用 MyAutoData
属性,如下所示:
public class MyTests
{
[Theory, MyAutoData]
public void GetThingsByUserId_ShouldReturnThings(IEnumerable<Thing> things)
{
things.First().UserId.Should().Be(1);
}
}
这是我正在尝试做的事情:
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,但事实并非如此。
我怎样才能做到这一点?
您可以通过创建自定义 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));
}
}
}
您还可以添加其他自定义项。请记住 the order matters.
然后,将测试方法更改为使用 MyAutoData
属性,如下所示:
public class MyTests
{
[Theory, MyAutoData]
public void GetThingsByUserId_ShouldReturnThings(IEnumerable<Thing> things)
{
things.First().UserId.Should().Be(1);
}
}