【发布时间】:2017-06-19 18:53:04
【问题描述】:
如何测试私有静态泛型方法?我的测试项目可以看到内部结构。如何测试这些方法?
internal class Foo {
// Non-static. This works!
private T TestThisMethod1<T>(T value) {
Console.WriteLine("Called TestThisMethod1");
return value;
}
// Static. Can't get this to work!
private static T TestThisMethod2<T>(T value) {
Console.WriteLine("Called TestThisMethod2");
return value;
}
// Static. Can't get this to work!
private static void TestThisMethod3<T>(T value) {
Console.WriteLine("Called TestThisMethod3");
}
// Static. Can't get this to work!
private static void TestThisMethod4<T, T2>(T value, T2 value2) {
Console.WriteLine("Called TestThisMethod4");
}
}
第一个例子有效。它不是静态的。这是https://msdn.microsoft.com/en-us/library/bb546207.aspx的例子。
[TestMethod]
public void PrivateStaticGenericMethodTest() {
int value = 40;
var foo = new Foo();
// This works. It's not static though.
PrivateObject privateObject = new PrivateObject(foo);
int result1 = (int)privateObject.Invoke("TestThisMethod1", new Type[] { typeof(int) }, new Object[] { value }, new Type[] { typeof(int) });
// Fails
int result2 = (int)privateObject.Invoke("TestThisMethod2", BindingFlags.Static | BindingFlags.NonPublic, new Type[] { typeof(int) }, new Object[] { value }, new Type[] { typeof(int) });
// Fails
PrivateType privateType = new PrivateType(typeof(Foo));
int result2_1 = (int)privateType.InvokeStatic("TestThisMethod2", new Type[] { typeof(int) }, new Object[] { value }, new Type[] { typeof(int) });
// Fails
int result2_2 = (int)privateType.InvokeStatic("TestThisMethod2", BindingFlags.Static | BindingFlags.NonPublic, new Type[] { typeof(int) }, new Object[] { value }, new Type[] { typeof(int) });
// Stopping here. I can't even get TestThisMethod2 to work...
}
我写这篇文章的目的并不是要质疑或争论测试私有方法的优点:这个主题已经被反复争论了。更重要的是,我写这个问题的目的是说“应该可以使用 PrivateObject 或 PrivateType 来做到这一点。那么,怎么做呢?”
【问题讨论】:
-
你的私有静态方法有消费者吗?如果不是,那为什么要测试它的行为?
-
一般私有方法通过调用它们的公共方法进行测试
-
没错,我通常遵循“仅测试公共方法”的规范。这些天来,如果可以避免的话,我讨厌公开任何东西。这种方法在代码中埋得很深。我应该能够使用 PrivateObject 或 PrivateType 单独测试此方法。
-
通用 T 项目是问题所在。对于那些它由于某种原因找不到方法。
标签: c# generics testing methods static