這些天來,我遇到了一個Team System Unit Testing問題。我發現,自動創建訪問器類忽略泛型約束 - 至少在以下情況:Private Accessor類忽略通用約束
假設你有下面的類:
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("[email protected]")]
public MyClass_Accessor();
public MyClass_Accessor(PrivateObject __p1);
public static PrivateType ShadowedType { get; }
public static MyClass_Accessor AttachShadow(object __p1);
[Shadowing("[email protected]")]
public T? MyMethod(string s);
}
}
正如你所看到的,有針對的MyMethod方法泛型類型參數沒有任何約束。
這是一個錯誤嗎?這是由設計嗎?誰知道如何解決這個問題?
「關閉,因爲無法修復」?太棒了。 – 2010-08-24 00:43:07