15.01.2013 Views

Foundations of Programming - Karl Seguin

Foundations of Programming - Karl Seguin

Foundations of Programming - Karl Seguin

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4 - Dependency Injection<br />

Sneak Peak at Unit Testing<br />

Talking about coupling with respect to unit testing is something <strong>of</strong> a chicken and egg problem – which to<br />

talk about first. I think it’s best to move ahead with coupling, provided we cover some basics about unit<br />

testing. Most importantly is that unit tests are all about the unit. You aren’t focusing on end-to-end<br />

testing but rather on individual behavior. The idea is that if you test each behavior <strong>of</strong> each method<br />

thoroughly and test their interaction with one another, you’re whole system is solid. This is tricky given<br />

that the method you want to unit test might have a dependency on another class which can’t be easily<br />

executed within the context <strong>of</strong> a test (such as a database, or a web-browser element). For this reason,<br />

unit testing makes use <strong>of</strong> mock classes – or pretend class.<br />

Let’s look at an example, saving a car’s state:<br />

public class Car<br />

{<br />

private int _id;<br />

public void Save()<br />

{<br />

if (!IsValid())<br />

{<br />

//todo: come up with a better exception<br />

throw new InvalidOperationException("The car must be in a valid<br />

state");<br />

}<br />

if (_id == 0)<br />

{<br />

_id = DataAccess.CreateInstance().Save(this);<br />

}<br />

else<br />

{<br />

DataAccess.CreateInstance().Update(this);<br />

}<br />

}<br />

}<br />

private bool IsValid()<br />

{<br />

//todo: make sure the object is in a valid state<br />

return true;<br />

}<br />

To effectively test the Save method, there are three things we must do:<br />

1. Make sure the correct exception is thrown when we try to save a car which is in an invalid state,<br />

2. Make sure the data access’ Save method is called when it’s a new car, and<br />

3. Make sure the Update method is called when it’s an existing car.<br />

What we don’t want to do (which is just as important as what we do want to do), is test the functionality<br />

<strong>of</strong> IsValid or the data access’ Save and Update functions (other tests will take care <strong>of</strong> those). The last<br />

point is important – all we want to do is make sure these functions are called with the proper<br />

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

27

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

Saved successfully!

Ooh no, something went wrong!