将接口映射到具体 class 时如何指定 Autofixture 的顺序?

How to dictate the order of Autofixture when mapping Interface to a concrete class?

    interface ILamp
    {
        bool IsWorking { get; set; }

        string LampModel { get; set; }
    }

    public string LampModel
        {
            get => _lampModel;
            set { _lampModel = IsWorking ? value : throw new Exception("its not in working."); }
        }

    class TestingClass
    {
        public ILamp lamp;
    }



        [Test]
        public void SimpleTest()
        {
            var Fixture = new Fixture();

            Fixture.Customizations.Add(new TypeRelay(typeof(ILamp), typeof(Lamp)));

            var fake = Fixture.Build<TestingClass>().Do(s => s.lamp.IsWorking = true).Create();
        }


我试图将我的具体 class 映射到接口,但正如在代码中看到的那样,为了设置 LampModel,您首先需要将 IsWorking 设置为 true。 我尝试在 .Do() 中这样做,但它给了我-- System.NullReferenceException : Object reference not set to an instance of an object 我认为这是由于 .Do() 运行 在定制之前或类似的原因。我该如何解决?

.Do() 自定义确实在创建自定义类型实例后立即运行,无法控制。

您可能应该尝试的是 customize/build Lamp 实例而不是 IsWorking 属性 的预期值,然后使用它,构建 TestingClass实例.

var fixture = new Fixture();
fixture.Customizations.Add(new TypeRelay(typeof(ILamp),typeof(Lamp)));
fixture.Customize<Lamp>(
    c => c.With(x => x.IsWorking, true)
          .With(x => x.LampModel));
                
var actual = fixture.Create<TestingClass>();

您可以查看 here 完整示例。