2011-02-03 85 views
3

我看起來basicly這樣的結構:因爲我需要做複雜單位的PrivateObject不找物業

abstract class A 
{ 
    protected string Identificator { get; set; } 

    private void DoSomething() 
    { 

     // ... 

     DoSomethingSpecific(); 
    } 

    protected abstract void DoSomethingSpecific(); 
} 

測試DoSomething的方法,以確保它的工作原理八方通以同樣的方式。這就是爲什麼我創建了以下存根。

public class AStub : A 
{ 
    protected override void DoSomethingSpecific() 
    { 
     // nothing to do 
    } 
} 

我使用PrivateObject類訪問的方法和類A的性質來實例化類AStub。這工作了一段時間,並由於某種原因現在崩潰,每當我嘗試訪問屬性或方法。測試

下面的代碼:

var sut = new CommonIodAdapterImpl(); 
var accessor = new PrivateObject(sut); 

accessor.SetProperty("Identificator", "blablub"); 
accessor.Invoke("DoSomething", null); 

// assert... 

它引發的異常是MissingMethodException告訴我,propertie或方法沒有被發現。但是,當我調試和檢查層次似乎是正確的拼寫。

謝謝你的幫助。

+1

假設我們假設'AStub`不是從`A`繼承的事實是這個問題代碼示例中的拼寫錯誤,它應該真的是`public class AStub:A`? – 2011-02-03 08:51:28

回答

9

您需要的PrivateType參數設置爲你的基類在該級別訪問私有成員。

var accessor = new PrivateObject(sut, new PrivateType(typeof(A))); 
1

這不應該是「公共課程AStub:A」嗎?

要解決缺少的方法異常,請再次編譯一切(!)。要麼你得到一些編譯器錯誤,告訴你什麼是錯誤的,否則錯誤將會消失。

如果它仍不起作用,請檢查您是否沒有多個程序集副本(包括GAC!),並在Deboug-Out-Window中觀察它是否從正確的路徑加載程序集。

1

我剛剛嘗試了類似的東西,我認爲這是因爲該屬性是受保護的而不是私人的。

我創建了自己的訪問在我的測試組裝

public class AAccessor : A 
{ 
    // use this instead of Identificator 
    public string IdentificatorAccessor 
    { 
     get { return this.Identificator; } 
     set { this.Identificator = value; } 
    } 

    // test this method in your unit test 
    public void DoSomethingAccessor() 
    { 
     this.DoSomethingSpecific() 
    } 

    // need this to satisfy the abstract class 
    protected override void DoSomethingSpecific() 
    { 
     // do nothing here 
    } 
}