I have read a lot about mocking, particularly using Rhino Mocks and have learned that Rhino Mocks can only mock interface methods which are virtual or virtual methods in concrete classes. I have read that the reason for this is because Rhino mocks can't intercept non-virtual methods and this is where I am stuck. What does it mean by intercepting methods? How does intercepting methods actually work with regards to mocking (Rhino Mocks in particular)
+1
A:
Basically the idea is that it creates a 'behind the scenes' class that overrides any virtual or interface methods and plugs in 'mock' code into them.
Highly simplified example/overview
if you have (based on your comment question)
public EmailHelper
{
public virtual int SendEmail( MailMessage message)
{
var server = ConnectToServer();
int statusCode = server.SubmitEmail( message );
return statusCode;
}
}
and then in a test (I forget Rhino's syntax for this, but this is close enough)
var mock = Mocks.CreateMockFor<EmailHelper>();
Expect.Call(mock.SendEmail).Return(5);
behind the scenes it will use reflection to load up the SomeClass Type
object, search it for interface implementations and virtual methods and generate a class something like
public MockEmailHelper
{
public override int SendEmail( MailMessage message )
{
return 5;
}
}
So as you can see, when you call the mock version of SendEmail, it wont connect to server etc, it will just do what you told it to, so you can test your code that depends on the 'email module' without actually sending email.
BioBuckyBall
2010-09-14 16:45:03
So mocking frameworks actually call implementations of your methods. Does it actually execute them? For example, what if I mocked up an e-mail method, would it send out e-mails?
Xaisoft
2010-09-14 16:58:51
No, thats the whole point...so that you don't depend on external systems. I will add more to help clarify, hold on....
BioBuckyBall
2010-09-14 17:07:26
Ok thanks, I will wait for your clarification.
Xaisoft
2010-09-14 17:13:30
Wow thanks for the explanation. It makes a lot more sense now. By not depending on external systems, you mean I am isolating different parts of the system as a whole correct? Based on your example above, mocking is more about testing the Interaction of the code, not the actual implementation?
Xaisoft
2010-09-14 17:24:20
Correct, isolation is the goal. In this case, you would be testing something **other than the email** that has a dependency on the EmailHelper. So you want to test the dependent object without actually running EmailHelper code.
BioBuckyBall
2010-09-14 17:37:48