Foundations of Programming - Karl Seguin
Foundations of Programming - Karl Seguin
Foundations of Programming - Karl Seguin
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Chapter 5 - Unit Testing<br />
you want to mock (an interface or a class – preferably an interface), tell it what method(s) you expect to<br />
be called, along with the parameters, execute the call, and have it verify that your expectations were<br />
met.<br />
Before we can get started, we need to give RhinoMocks access to our internal types. This is quickly<br />
achieved by adding [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] to our<br />
Properties/AssemblyInfo.cs file.<br />
Now we can start coding by writing a test to cover the update path <strong>of</strong> our Save method:<br />
[TestFixture]<br />
public class CarTest<br />
{<br />
[Test]<br />
public void SaveCarCallsUpdateWhenAlreadyExistingCar()<br />
{<br />
}<br />
}<br />
MockRepository mocks = new MockRepository();<br />
IDataAccess dataAccess = mocks.CreateMock();<br />
ObjectFactory.InjectStub(type<strong>of</strong>(IDataAccess), dataAccess);<br />
Car car = new Car();<br />
dataAccess.Update(car);<br />
mocks.ReplayAll();<br />
car.Id = 32;<br />
car.Save();<br />
mocks.VerifyAll();<br />
ObjectFactory.ResetDefaults();<br />
Once a mock object is created, which took 1 line <strong>of</strong> code to do, we inject it into our dependency<br />
injection framework (StructureMap in this case). When a mock is created, it enters record-mode, which<br />
means any subsequent operations against it, such as the call to dataAccess.UpdateCar(car), is<br />
recorded by RhinoMocks (nothing really happens since dataAcces is simply a mock object with no real<br />
implementation). We exit record-mode by calling ReplayAll, which means we are now ready to<br />
execute our real code and have it verified against the recorded sequence. When we then call<br />
VerifyAll after having called Save on our Car object, RhinoMocks will make sure that our actual call<br />
behaved the same as what we expected. In other words, you can think <strong>of</strong> everything before ReplayAll<br />
as stating our expectations, everything after it as our actual test code with VerifyAll doing the final<br />
check.<br />
<strong>Foundations</strong> <strong>of</strong> <strong>Programming</strong> Copyright © <strong>Karl</strong> <strong>Seguin</strong> www.codebetter.com<br />
39