2008-09-15 81 views
4

這些天來,我遇到了一個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方法泛型類型參數沒有任何約束。

這是一個錯誤嗎?這是由設計嗎?誰知道如何解決這個問題?

回答

3

我投票的bug。我不明白這是如何設計的。

1

我沒有驗證一切,但它看起來像調用:

TestEnum? e1 = target.MyMethod("item2"); 

使用類型推斷來確定泛型類型PARAM T.嘗試不同的調用方法在測試如果可能的話:

TestEnum? e1 = target.MyMethod<TestEnum>("item2"); 

這可能會產生不同的結果。

希望有幫助!

0

使用msdn上的泛型搜索單元測試。這是一個已知的限制。投票決定Microsoft Connect,因爲它肯定需要解決。

1

看起來像一個錯誤。解決方法是將方法更改爲internal,並將[assembly: InternalsVisibleTo("MyLibrary.Test")]添加到包含待測試類的程序集。

這將是我首選的測試非公開方法的方式,因爲它產生更清晰的單元測試。