AutoFixture无法创建不可变对象

问题描述 投票:0回答:1

[我正在C#8.0中使用AutoFixture编写一些测试的代码,但是我想关于类继承的问题很多。

例如,我有以下课程:

public class Parent
{
  public Guid Id {get; protected set;}
  public int Age {get; protected set;}

  public void SetAge(int age)
  {
      this.Age = age;
  }
}

和子班

public class Child: Parent
{
  public string name {get; private set;}

  private Child() //I Need this because Migrations
  { 
  }
}

之后,我使用AutoFixture测试我的课程:

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

和BOOM!夹具尝试创建对象时,出现错误

"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类中的公共构造函数更改了private,则在设置Age时,该对象将创建为Empty。如果我不使用SetAge方法,则创建该对象不会出现问题。

有人遇到这个问题吗?使用继承类时是否需要在AutoFixture中设置一些属性?

谢谢

c# .net .net-core autofixture
1个回答
0
投票

好,宝贝!

我发现了:

Force AutoFixture to use the greediest constructor

还有!我解决了我的问题!

© www.soinside.com 2019 - 2024. All rights reserved.