简体   繁体   English

AutoFixture 无法创建不可变对象

[英]AutoFixture can't create immutable object

I'm coding some tests using AutoFixture in C# 8.0 but I'm had been problems, I guess, about class inheritance.我正在使用 C# 8.0 中的 AutoFixture 编写一些测试,但我想我遇到了关于类继承的问题。

For example, I have these classes:例如,我有这些类:

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

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

and the child class和儿童班

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

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

After it, I use AutoFixture to test my class:之后,我使用 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>();

and BOOM!和繁荣! I get an error at the moment when the fixture tries to create the 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.

If I change private for the public constructor in Child class, when I set the Age, the object is created Empty.如果我为 Child 类中的公共构造函数更改私有,则当我设置年龄时,该对象将创建为空。 If I don't use SetAge method, the object is created without problems.如果我不使用 SetAge 方法,则创建对象没有问题。

Someone had this problem?有人遇到过这个问题吗? Do I need to set some property in AutoFixture when I Use inheritance classes?使用继承类时是否需要在 AutoFixture 中设置某些属性?

Thank you谢谢

Alright, babe!好的,宝贝!

I found this:我找到了这个:

Force AutoFixture to use the greediest constructor 强制 AutoFixture 使用最贪婪的构造函数

And Gotcha!还有问题! I solve my problem!我解决了我的问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM