C#に次のコードがあるとしましょう。
public class AppleTree
{
public AppleTree()
{
}
public string GetApple
{
return new Fruit("Apple").ToString();
}
}
ここで、Fruitは、インターフェースを持たないサードパーティのクラスです。
AppleTreeクラスの単体テストを作成したいのですが、Fruitクラスを実行したくありません。代わりに、Fruitクラスを注入して、テストでモックできるようにします。
どうすればこれを行うことができますか?リンゴを作成するファクトリを作成してから、次のようにこのファクトリにインターフェイスを追加できます。
public class FruitFactory : IFruitFactory
{
Fruit CreateApple()
{
return new Fruit("Apple");
}
}
これで、IFruitFactoryをAppleTreeに挿入し、新しいFruitの代わりにCreateAppleを次のように使用できます。
public class AppleTree
{
private readonly IFruitFactory _fruitFactory;
public AppleTree(IFruitFactory fruitFactory)
{
_fruitFactory = fruitFactory
}
public string GetApple
{
return _fruitFactory.CreateApple().ToString();
}
}
さて、私の質問です。工場を作成せずにこれを行う良い方法はありますか?たとえば、Ninjectのような依存性注入の名声を何らかの方法で使用できますか?