15.01.2013 Views

Foundations of Programming - Karl Seguin

Foundations of Programming - Karl Seguin

Foundations of Programming - Karl Seguin

SHOW MORE
SHOW LESS

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 />

If we changed our Save function to throw an exception if the returned id was invalid, our test would<br />

look like:<br />

[TestFixture]<br />

public class CarTest<br />

{<br />

private MockRepository _mocks;<br />

private IDataAccess _dataAccess;<br />

}<br />

[SetUp]<br />

public void SetUp()<br />

{<br />

_mocks = new MockRepository();<br />

_dataAccess = _mocks.CreateMock();<br />

ObjectFactory.InjectStub(type<strong>of</strong>(IDataAccess), _dataAccess);<br />

}<br />

[TearDown]<br />

public void TearDown()<br />

{<br />

_mocks.VerifyAll();<br />

}<br />

[Test, ExpectedException("CodeBetter.<strong>Foundations</strong>.PersistenceException")]<br />

public void SaveCarCallsSaveWhenNew()<br />

{<br />

Car car = new Car();<br />

Expect.Call(_dataAccess.Save(car)).Return(0);<br />

_mocks.ReplayAll();<br />

car.Save();<br />

}<br />

In addition to showing how you can test for an exception (via the ExpectedException attribute),<br />

we’ve also extracted the repetitive code that creates, sets up and verifies the mock object into the<br />

SetUp and TearDown methods.<br />

More on nUnit and RhinoMocks<br />

So far we’ve only looked at the basic features <strong>of</strong>fered by nUnit and RhinoMocks, but there’s a lot more<br />

that can actually be done with them. For example, RhinoMocks can be setup to ignore the order <strong>of</strong><br />

method calls, instantiate multiple mocks but only replay/verify specific ones, or mock some but not<br />

other methods <strong>of</strong> a class (a partial mock).<br />

Combined with a utility like NCover, you can also get reports on your tests coverage. Coverage basically<br />

tells you what percentage <strong>of</strong> an assembly/namespace/class/method was executed by your tests. NCover<br />

has a visual code browser that’ll highlight any un-executed lines <strong>of</strong> code in red. Generally speaking, I<br />

dislike coverage as a means <strong>of</strong> measuring the completeness <strong>of</strong> unit tests. After all, just because you’ve<br />

executed a line <strong>of</strong> code does not mean you’ve actually tested it. What I do like NCover for is to highlight<br />

any code that has no coverage. In other words, just because a line <strong>of</strong> code or method has been executed<br />

<strong>Foundations</strong> <strong>of</strong> <strong>Programming</strong> Copyright © <strong>Karl</strong> <strong>Seguin</strong> www.codebetter.com<br />

41

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!