What do you do when you are writing a test for a piece of
code that calls out to an ‘out of your control’ service such as a web service
or email server? If you are like most of
us, you simply allow your test to make the call and ‘hope’ that the service is
up. However, this is really bad. Having your test make calls to a service that
is out of your control can lead to ‘spontaneous’ breakages. It also puts dependencies in your test,
another bad thing.
If you are using RhinoMocks (could also use NMock, but I like
RhinoMocks) and StructureMap (could use any IoC/DI container, but I like
StructureMap) it is pretty easy and straight forward to ‘Mock’ out those
services.
Quick background on this code.
This test was writing to verify that when a web service is down (IMilesServiceContract) that an email (IEmailer) will be sent. Because I cannot force the service to be
down, I have to ‘fake’ it out with Mocks.
And because I don’t care that the email actually gets sent I also will
fake this out.
Below is the code that will allow you to ‘Mock’ out a web
service and them email service
Code Explained
Generating the stubs
Because I don’t want to use the actual concrete classes, I am going to create
stubs of them via RhinoMocks
Setting the
expectations
Once I have the stubs created, I want to set the expectations on the methods
for each of the stubs that I want to be called.
I don’t care about the actual parameter values used, so that is why I use
the IgnoreArguments method. It is here you set the default return value.
Injecting the stubs
into StructureMap
In order for StructureMap to use the stubs, you need to ‘inject’ them in so
that when the next call to create the object via the ObjectFactory is called
the stubs will be returned.
ReplayAll
This tells the RhinoMocks engine that all setup work is finished and to set the
mocking eninge
Few Gotcha’s to look out for
- You must set any expectations PRIOR to using the
object/stub. Otherwise you will get an
exception.
- It’s best/easiest to inject interfaces into
StructureMap. I have issues when ever I inject
concrete classes.
Till next time,
Posted
07-24-2007 9:32 AM
by
Derik Whittaker