2011-09-28 63 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