Search code examples
c#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();
        }


I tried to map my concrete class to interface but as it can be seen in the code in order to set LampModel you first need to make IsWorking to true. I try to do that in .Do() but it gives me-- System.NullReferenceException : Object reference not set to an instance of an object which I think due to .Do() running before the customization or something like that. How can I fix it?


Solution

  • The .Do() customization indeed runs right after the customized type instance is created, and there is no way to control that.

    What you probably should try, is to customize/build the Lamp instance instead with the expected value for the IsWorking property and then using it, build the TestingClass instance.

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

    You can check here the full example.