经过3个多小时的挫折,我决定问。
我有这个简单的类要测试:
public class Organizer {
private static bool Bongo(String p) {
return p != null && p.Length >= 5;
}
private static int ValidateArgs(String[] args) {
return args.Length;
}
}
我有这段代码使用 MSTest 来测试静态方法:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
public class OrganizerTest {
[TestMethod]
public void TestBongo() {
PrivateType psOrganizers = new PrivateType(typeof(Organizer));
// This one works fine.
Assert.IsTrue(Convert.ToBoolean(psOrganizers.InvokeStatic("Bongo", "ABCDEFG")));
// Fails with: "System.MissingMethodException: Method 'Organizer.Bongo' not Found.
Assert.IsFalse(Convert.ToBoolean(psOrganizers.InvokeStatic("Bongo", null)));
}
[TestMethod]
public void TestBodo() {
PrivateType psOrganizers = new PrivateType(typeof(Organizer));
String[] fakeArray = new String[] { "Pizza" };
// Fails with: "System.MissingMethodException: Method 'Organizer.ValidateArgs' not Found.
int result1 = Convert.ToInt32(psOrganizers.InvokeStatic("ValidateArgs", fakeArray));
// Fails with: "System.MissingMethodException: Method 'Organizer.ValidateArgs' not Found.
int result2 = Convert.ToInt32(psOrganizers.InvokeStatic("ValidateArgs", "A", "B", "C", "D"));
// Fails with: "System.MissingMethodException: Method 'Organizer.ValidateArgs' not Found.
int result3 = Convert.ToInt32(psOrganizers.InvokeStatic("ValidateArgs", new Object[] { "A", "B", "C", "D" }));
Assert.IsTrue(result1 == 1 && result2 == 4 && result3 == 4);
}
}
除了 TestBongo 中的第一个 Assert 之外,其他所有 Assert 都因 MissingMethodException 而失败。有许多 InvokeStatic() 重载,我怀疑编译器可能没有选择我期望的那个。
顺便说一句,请不要告诉我不要测试私有方法。我不是在寻找辩论。:)
谢谢你。