AutoFixture 无法创建不可变 object
AutoFixture can't create immutable object
我正在使用 C# 8.0 中的 AutoFixture 编写一些测试代码,但我猜我遇到了关于 class 继承的问题。
例如,我有这些 classes:
public class Parent
{
public Guid Id {get; protected set;}
public int Age {get; protected set;}
public void SetAge(int age)
{
this.Age = age;
}
}
和 child class
public class Child: Parent
{
public string name {get; private set;}
private Child() //I Need this because Migrations
{
}
}
之后,我使用 AutoFixture 来测试我的 class:
var fixture = new Fixture();
fixture.Behaviors.Remove(new ThrowingRecursionBehavior());
fixture.Behaviors
.OfType<ThrowingRecursionBehavior>()
.ToList()
.ForEach(b => fixture.Behaviors.Remove(b));
fixture.Register<Parent>(() => null);
fixture.Behaviors.Add(new OmitOnRecursionBehavior(recursionDepth: 3));
fixture.Customize<Child>(c => c.FromFactory(new MethodInvoker(new GreedyConstructorQuery())));
fixture.Customize<Child>(ce => ce.Do(x => x.SetAge(10));
var childObject = fixture.Create<Child>();
砰!当 fixture 尝试创建 object
时出现错误
"AutoFixture was unable to create an instance from the project, most likely because it has no public constructor, is an abstract or non-public type.
如果我在 Child class 中为 public 构造函数更改私有,当我设置年龄时,object 被创建为空。如果我不使用 SetAge 方法,则创建 object 没有问题。
有人遇到过这个问题吗?使用继承classes时是否需要在AutoFixture中设置一些属性?
谢谢
好的,宝贝!
我发现了这个:
Force AutoFixture to use the greediest constructor
明白了!我的问题解决了!
我正在使用 C# 8.0 中的 AutoFixture 编写一些测试代码,但我猜我遇到了关于 class 继承的问题。
例如,我有这些 classes:
public class Parent
{
public Guid Id {get; protected set;}
public int Age {get; protected set;}
public void SetAge(int age)
{
this.Age = age;
}
}
和 child class
public class Child: Parent
{
public string name {get; private set;}
private Child() //I Need this because Migrations
{
}
}
之后,我使用 AutoFixture 来测试我的 class:
var fixture = new Fixture();
fixture.Behaviors.Remove(new ThrowingRecursionBehavior());
fixture.Behaviors
.OfType<ThrowingRecursionBehavior>()
.ToList()
.ForEach(b => fixture.Behaviors.Remove(b));
fixture.Register<Parent>(() => null);
fixture.Behaviors.Add(new OmitOnRecursionBehavior(recursionDepth: 3));
fixture.Customize<Child>(c => c.FromFactory(new MethodInvoker(new GreedyConstructorQuery())));
fixture.Customize<Child>(ce => ce.Do(x => x.SetAge(10));
var childObject = fixture.Create<Child>();
砰!当 fixture 尝试创建 object
时出现错误"AutoFixture was unable to create an instance from the project, most likely because it has no public constructor, is an abstract or non-public type.
如果我在 Child class 中为 public 构造函数更改私有,当我设置年龄时,object 被创建为空。如果我不使用 SetAge 方法,则创建 object 没有问题。
有人遇到过这个问题吗?使用继承classes时是否需要在AutoFixture中设置一些属性?
谢谢
好的,宝贝!
我发现了这个:
Force AutoFixture to use the greediest constructor
明白了!我的问题解决了!