依存関係を分離するためにプロジェクトに何百ものインターフェイスが必要な場合、設計に問題がある可能性があることに気付きました。これは、これらのインターフェイスの多くが最終的に 1 つのメソッドしか持たない場合に特に当てはまります。これに代わる方法は、オブジェクトでイベントを発生させ、依存関係をそれらのイベントにバインドすることです。例として、データの永続化をモックアウトしたいとしましょう。これを行う完全に合理的な方法の 1 つは、次のようにすることです。
public interface IDataPersistor
{
void PersistData(Data data);
}
public class Foo
{
private IDataPersistor Persistor { get; set; }
public Foo(IDataPersistor persistor)
{
Persistor = persistor;
}
// somewhere in the implementation we call Persistor.PersistData(data);
}
インターフェイスやモックを使用せずにこれを行う別の方法は、次のようにすることです。
public class Foo
{
public event EventHandler<PersistDataEventArgs> OnPersistData;
// somewhere in the implementation we call OnPersistData(this, new PersistDataEventArgs(data))
}
次に、私たちのテストでは、モックを作成する代わりにこれを行うことができます:
Foo foo = new Foo();
foo.OnPersistData += (sender, e) => { // do what your mock would do here };
// finish your test
これは、モックを過度に使用するよりもクリーンであることがわかりました。