Hol*_*olf 4 .net c# 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我希望 IEnumerable<Thing> things传递到测试中的参数的 a 均为UserId1,但事实并非如此。
我怎样才能做到这一点?
您可以通过创建自定义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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
您还可以添加其他自定义。请记住顺序很重要。
然后,将测试方法更改为使用MyAutoData属性,如下所示:
public class MyTests
{
[Theory, MyAutoData]
public void GetThingsByUserId_ShouldReturnThings(IEnumerable<Thing> things)
{
things.First().UserId.Should().Be(1);
}
}
Run Code Online (Sandbox Code Playgroud)