【问题标题】:AutoFixture can't create immutable objectAutoFixture 无法创建不可变对象
【发布时间】:2020-02-14 12:37:26
【问题描述】:

我正在使用 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>();

然后砰!夹具尝试创建对象时出现错误

"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 中设置一些属性?

谢谢

【问题讨论】:

  • 最后一句,“如果我不使用 SetAge 方法,对象创建没有问题。”,你是说如果你删除上面的自定义,那调用 SetAge(10),但保留构造函数是私有的,fixture.Create&lt;Child&gt;(); 能够构造一个 Child?
  • 是的!这很奇怪......我在谷歌上找到了这段代码,但错误仍在继续......fixture.Register(fixture.Create); fixture.Build();

标签: c# .net .net-core autofixture


【解决方案1】:

好的,宝贝!

我发现了这个:

Force AutoFixture to use the greediest constructor

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多