Property Injection with AutoFixture

I've been fighting with the following issue for a day or so now. Despite having used AutoFixture for years, I can't get my head around this issue.

I have an abstract class:

public abstract class AbstractClass 
{
   public IChildClass Child {get; set;}
};

The IChildInterface:

public interface IChildClass
{
   string Name {get; set;}
}

The implementation of the interface:

public class ChildClass : IChildClass
{
   public string Name {get; set;}
}

I then have a derived class of AbstractClass:

public class MyClass : AbstractClass
{
   public MyClass()
   {
      Initialize();
   }

   private void Initialize()
   {
      var nameOfChild = Child.Name;
   }
}

In my unit test for MyClass I do the following:

var fixture = new Fixture().Customize(new AutoMoqCustomization());

var sut = fixture.Create<MyClass>();

But get an NullReferenceException on Child.Name. I've tried using Register and Customize for IChildClass and AbstractClass, no luck. Even a custom implementation of ISpecimenBuilder, doesn't help in this case.

Does anyone have a good idea on how to get around this?

Upvotes: 1

Views: 610

Answers (1)

Ruskin
Ruskin

Reputation: 1504

The above code will never work because Initialize gets called in the Ctor. Autofixture is initializing the object and the property hasn't been injected just as yet. There are several work arounds for the above but as it stands... Child will always be null in the Initialize method.

Upvotes: 1

Related Questions