Lets say I have the following code in C#:
public class AppleTree
{
public AppleTree()
{
}
public string GetApple
{
return new Fruit("Apple").ToString();
}
}
where Fruit is a third party class that does not have an interface.
I want to create a unit test for the AppleTree class but I do not want to run the Fruit class. Instead I would like to inject the Fruit class so that I can mock it in the tests.
How should I go about doing this? I can create a factory that creates apples and then add an interface to this factory like:
public class FruitFactory : IFruitFactory
{
Fruit CreateApple()
{
return new Fruit("Apple");
}
}
Now I can inject IFruitFactory into the AppleTree and use the CreateApple instead of new Fruit as:
public class AppleTree
{
private readonly IFruitFactory _fruitFactory;
public AppleTree(IFruitFactory fruitFactory)
{
_fruitFactory = fruitFactory
}
public string GetApple
{
return _fruitFactory.CreateApple().ToString();
}
}
Now to my question: Is there a good way of doing this without having to create the factory? Can I for example use a dependency injector famework like Ninject in some way?
See
Ninject.Extensions.Factory– with it, you haveFunc<T>ctor arguments and the Abstract Factory is generated behind the scenes (a la @Nenad’s +1’d answer)(You can also define an Abstract Factory interface and have Ninject.Extensions.Factory implement it.