你好,
```C#
[测试夹具]
公共类 TestAutoFixture {
public class TestClass
{
public string Property { get; set; }
}
[Test]
public void Test()
{
var f = new Fixture();
f.Customize<TestClass>(composer => composer.FromFactory(() => new TestClass { Property = "foobar" }));
var o = f.Create<TestClass>();
Assert.That(o.Property, Is.EqualTo("foobar"));
}
}
``
此测试在 .NET Core 2 上使用 4.0.0-rc1 失败
我认为这要么具有误导性(或记录不充分)要么已损坏。
编辑:它没有坏,请参阅下面的评论。
我注意到如果我在FromFactory
方法之后添加.Without(_ => _.Property)
,它会按预期工作。
我认为这非常违反直觉,但由于它不是错误,我们可以关闭它。
嗯,这可能是我们的文档有问题☺️
默认情况下,AutoFixture 自动使用公共设置器填充属性,除非您通过设置fixture.OmitAutoProperties = true
禁用该行为。 composer.FromFactory()
方法允许您指定如何激活特定类型的实例,但稍后仍会为该对象分配属性。
实际上,正确的 AutoFixture API 用法取决于场景。 上述场景中最“惯用”的用法如下:
```c#
f.定制
.FromFactory(() => new TestClass())
.With(x => x.Property, "foobar"));
or even the simplified one as AutoFixture will automatically pick up that constructor:
```c#
f.Customize<TestClass>(c => c
.With(x => x.Property, "foobar"));
或者,如果需要,您可以简单地禁用自动属性填充:
```c#
f.定制
.FromFactory(() => new TestClass { Property = "foobar" })
.OmitAutoProperties());
However, in this case, probably, the `Customize<>()` API is an overhead. Instead, it's simpler to use the `fixture.Register()` method as it allows to use the constructed instance "as-is" without any post-processing:
```c#
f.Register(() => new TestClass { Property = "foobar" });
一开始可能会混淆到底哪个 API 更适合,但后来应该会更容易😉所有这些 API 都提供了灵活性,并且在不同的场景中,不同的选项看起来更好。
如果您还有一些问题需要澄清,请告诉我,我很乐意为您提供帮助。
PS以下链接也可能有帮助:
PPS composer.Without(x => x.Property)
起作用的原因是该表达式禁用了特定属性/字段的自动属性。 在这种情况下,AutoFixture 不会用自动生成的值覆盖初始对象值。
非常感谢您提供这个令人难以置信的答案! 你太棒了 :)
最有用的评论
嗯,这可能是我们的文档有问题☺️
默认情况下,AutoFixture 自动使用公共设置器填充属性,除非您通过设置
fixture.OmitAutoProperties = true
禁用该行为。composer.FromFactory()
方法允许您指定如何激活特定类型的实例,但稍后仍会为该对象分配属性。实际上,正确的 AutoFixture API 用法取决于场景。 上述场景中最“惯用”的用法如下:
```c#(c => c
f.定制
.FromFactory(() => new TestClass())
.With(x => x.Property, "foobar"));
或者,如果需要,您可以简单地禁用自动属性填充:(c => c
```c#
f.定制
.FromFactory(() => new TestClass { Property = "foobar" })
.OmitAutoProperties());
一开始可能会混淆到底哪个 API 更适合,但后来应该会更容易😉所有这些 API 都提供了灵活性,并且在不同的场景中,不同的选项看起来更好。
如果您还有一些问题需要澄清,请告诉我,我很乐意为您提供帮助。
PS以下链接也可能有帮助:
PPS
composer.Without(x => x.Property)
起作用的原因是该表达式禁用了特定属性/字段的自动属性。 在这种情况下,AutoFixture 不会用自动生成的值覆盖初始对象值。