2011-09-28 44 views
2

我有這種類型的屬性:是否有可能來嘲笑一種使用Rhino.Mocks

[RequiresAuthentication] 
public class MobileRunReportHandler : IMobileRunReportHandler 
{ 
    public void Post(MobileRunReport report) 
    { 
    ... 
    } 
} 

我嘲笑它像這樣:

var handler = MockRepository.GenerateStub<IMobileRunReportHandler>(); 
handler.Stub(x => x.Post(mobileRunReport)); 

的問題是,所產生的模擬不屬於RequiresAuthentication屬性。我如何解決它?

謝謝。

編輯

我想嘲笑的類型與RequiresAuthentication屬性歸因,因爲我是測試代碼使用這個屬性。我想知道如何更改我的嘲笑代碼,以指示嘲笑框架相應地生成模擬。

+1

的可能重複[嘲諷屬性 - C#](http://stackoverflow.com/questions/319002/mocking-attributes-c) – msarchet

+0

我會很高興如果您向我展示該帖子的確切位置包含我的問題答案,請與您同意。謝謝。 – mark

+0

在什麼情況下,您需要將該類歸入「RequiresAuthentication」?你能詳細說明一點嗎? – Jeroen

回答

1

在運行時將Attribute添加到類型,然後使用反射來獲取它是不可能的(例如,請參閱this後)。到RequiresAuthentication屬性添加到存根最簡單的方式是自己創建這個存根:

// Define this class in your test library. 
[RequiresAuthentication] 
public class MobileRunReportHandlerStub : IMobileRunReportHandler 
{ 
    // Note that the method is virtual. Otherwise it cannot be mocked. 
    public virtual void Post(MobileRunReport report) 
    { 
     ... 
    } 
} 

... 

var handler = MockRepository.GenerateStub<MobileRunReportHandlerStub>(); 
handler.Stub(x => x.Post(mobileRunReport)); 

或者你可以生成用於MobileRunReportHandler類型存根。但你不得不做出Post方法virtual

[RequiresAuthentication] 
public class MobileRunReportHandler : IMobileRunReportHandler 
{ 
    public virtual void Post(MobileRunReport report) 
    { 
     ... 
    } 
} 

... 

var handler = MockRepository.GenerateStub<MobileRunReportHandler>(); 
handler.Stub(x => x.Post(mobileRunReport)); 
+0

對不起。我就是不明白。由Rhino.Mocks生成的存根是動態類型的,即類型是在運行時使用'Reflection.Emit'工具創建的,該工具允許根據我們的需要設置一個動態類型。這是Rhino.Mocks是否知道利用'Reflection.Emit'這個能力的問題。 – mark