Is it possible to mock a type with an attribute using Rhino.Mocks
I have this type:
[RequiresAuthentication]
public class MobileRunReportHandler : IMobileRunReportHandler
{
public void Post(MobileRunReport report)
{
...
}
}
I am mocking it like so:
var handler = Moc开发者_运维技巧kRepository.GenerateStub<IMobileRunReportHandler>();
handler.Stub(x => x.Post(mobileRunReport));
The problem is that the produced mock is not attributed with the RequiresAuthentication
attribute. How do I fix it?
Thanks.
EDIT
I want the mocked type to be attributed with the RequiresAuthentication
attribute, because the code that I am testing makes use of this attribute. I would like to know how can I change my mocking code to instruct the mocking framework to attribute the produced mock accordingly.
Adding an Attribute
to a type at runtime and then getting it using reflection isn't possible (see for example this post). The easiest way to add the RequiresAuthentication
attribute to the stub is to create this stub yourself:
// 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));
Or you could generate a stub for the MobileRunReportHandler
type. But you'd have to make its Post
method virtual
:
[RequiresAuthentication]
public class MobileRunReportHandler : IMobileRunReportHandler
{
public virtual void Post(MobileRunReport report)
{
...
}
}
...
var handler = MockRepository.GenerateStub<MobileRunReportHandler>();
handler.Stub(x => x.Post(mobileRunReport));
精彩评论