C#のprivateでgenericなメソッドをテストしたい
メソッドの単体テストでprivateでgenericなメソッドをテストしたかったので調べた結果をメモしておきます。
テストしたいメソッドの形式
テストしたいメソッドは private になっています。
この場合、PrivateObjectを使うことでテスト可能のようです。
Genericsを含むメソッドの実行についてはリフレクションを実行するということだったので、次のように組み合わせました。
public class FooService { private IEnumerable<T> BarFunc<T>(string stringParam) { List<T> data = new List<T>(); : :
テストコード
ソースコード中の CustomType は、
Dynamicを使うようなブログもあったのですが、またの機会に調べてみようと思います。
[TestMethod] public void TestBarFunc() { string stringParam = "hogehoge"; FooService fooService = new FooService(); var pbObj = new PrivateObject(fooService); MethodInfo targetMethod = importService.GetType().GetMethod( "BarFunc", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance); if (targetMethod == null) { Assert.Fail("Could not find method"); } MethodInfo genericFooMethod = targetMethod.MakeGenericMethod(new Type[] { typeof(CustomType) } ); IEnumerable<CustomType> data = (IEnumerable<CustomType>)genericFooMethod.Invoke(fooService, new object[] { stringParam });