这些天,我遇到了一个关于团队系统单元测试的问题。
假设您有以下类:
namespace MyLibrary
{
public class MyClass
{
public Nullable<T> MyMethod<T>(string s) where T : struct
{
return (T)Enum.Parse(typeof(T), s, true);
}
}
}如果您想测试MyMethod,可以使用以下测试方法创建一个测试项目:
public enum TestEnum { Item1, Item2, Item3 }
[TestMethod()]
public void MyMethodTest()
{
MyClass c = new MyClass();
PrivateObject po = new PrivateObject(c);
MyClass_Accessor target = new MyClass_Accessor(po);
// The following line produces the following error:
// Unit Test Adapter threw exception: GenericArguments[0], 'T', on
// 'System.Nullable`1[T]' violates the constraint of type parameter 'T'..
TestEnum? e1 = target.MyMethod<TestEnum>("item2");
// The following line works great but does not work for testing private methods.
TestEnum? e2 = c.MyMethod<TestEnum>("item2");
}运行测试将失败,并显示上述代码片段注释中提到的错误。问题出在Visual Studio创建的访问器类。如果你进入它,你会看到下面的代码:
namespace MyLibrary
{
[Shadowing("MyLibrary.MyClass")]
public class MyClass_Accessor : BaseShadow
{
protected static PrivateType m_privateType;
[Shadowing(".ctor@0")]
public MyClass_Accessor();
public MyClass_Accessor(PrivateObject __p1);
public static PrivateType ShadowedType { get; }
public static MyClass_Accessor AttachShadow(object __p1);
[Shadowing("MyMethod@1")]
public T? MyMethod(string s);
}
}如您所见,MyMethod方法的泛型类型参数没有约束。
那是个bug吗?这是设计出来的吗?谁知道如何解决这个问题呢?
发布于 2008-09-15 17:23:16
我投票给bug。我不明白这怎么可能是故意的。
发布于 2009-07-28 19:29:48
发布于 2008-10-03 19:18:47
TestEnum? e1 = target.MyMethod("item2");使用类型推断来确定泛型类型param T。如果可能,请尝试在测试中以不同的方式调用该方法:
TestEnum? e1 = target.MyMethod<TestEnum>("item2");这可能会产生不同的结果。
希望这能有所帮助!
https://stackoverflow.com/questions/64813
复制相似问题