如何测试私有静态泛型方法?内部对我的测试项目是可见的。如何测试这些方法?在C#中测试私有静态泛型方法
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隔离测试此方法。 – clarionprogrammer