Touching a hot iron

December 14, 2008 20:36

So, here we go. Having touched the topic of unit testing, we cannot bypass mocking, can we?

Most of methods use other types to carry on. In order to test something in isolation we need to remove all dependencies, thus the need for fake implementations. Obviously you can write your own fake implementations (so called stubs) but it’s more sort of a dog-walking-on-two-legs solution that is just spooky.

Sooner or later, your subs will end up with logic in them (perhaps even a type hierarchy). Then every stub gets responsible for several similar tests, then production code gets changed and lo and behold, you have some interesting refactoring in hands.


Extirpate hand written stubs. A mocking framework would take all that plumbing upon itself.

Which one to use?

Hmm, good question. A few of the coming posts will be covering the four favorites: NMock2, Rhino Mocks, Typemock Isolator and Moq. To make that review more impartial, the same test scenario will be used everywhere.

And in order to make it more fun this scenario will be taken from real life.


(c) www.colorado.edu
(Image from http://www.colorado.edu. It's not about touching an iron though, but the difference is minimal)

Neurophysiological part.


Just imagine how complicated it is. Your brain sends a signal down to the spinal cord that in turn sends it to your hand. Some muscles in the hand contract; the hand moves and touches the hot iron. Boom!

Your body is crammed with special receptors called nociceptors for stuff like pain. In those guys pain gets detected and transduced into electrical potential that travels at rate of about 20 meters per second. (There is another type of nociceptors that transmits signals 10 times slower – that’s why pain usually comes in two waves. Although please don’t really try this, at least until you read over this miniseries.)

So, you’ve touched the iron and thermal nociceptors of your hand get activated by noxious heat. Electrical signals go from the hand up to the spinal cord and then divide. One part retraces to jerk back the hand. Another part goes further up to a special zone of the brain where you identify the problem and yell.


Unit testing.


With so complicated interaction we need to mock some of the parts and actually test this yell in isolation. We mock a hand that would just throw an exception as if it touches a hot iron. Also, for simplicity, let’s count brain and spinal cord as one essence (bear with me, medical pundits!) and have a brain with only one hand and a mouth.


public void TouchIron(Iron iron)
{
    try {
        _hand.TouchIron(iron);
    }
    catch(BurnException) {
        _mouth.Yell();
    }
}

Isn't it slick? Next week we'll take a peek at how it looks in different mocking frameworks.

 


Comments are closed