Mock the TextBox

Theres a fairly standard technique for testing whether some system object is used correctly. You build a Mock Object, an object that mimics the system object just enough to detect whether its being sent the right messages. Ive never used the technique in a strongly typed language, so its time to find out what it takes.

Dave Thomas and Andy Hunt, the Pragmatic Programmers, published an article about mock objects in IEEE Software in May/June 2002. An online copy can be found at .

My intention is just this, based on a couple of experiments that I havent written up. The KeyDownHandler uses only a couple of the features of the TextBox, so I should be able to mock up just those features. In a reasonable language, that would be easy: just plug in a MockTextBox that responds to those messages and let it go. In a strongly-typed language, we cant just do that: the language wants us to support all the known methods of the original objects type. Therefore, Im going to do this in two steps:

  1. Isolate the usage. Note in the code above that the KeyDownHandler really only refers to the textbox in a couple of important places: it reads the data at the beginning, and it sets the data back at the end. (The uses in the middle of the method are just there for early manual testing. I should take them out anyway.)

  2. Build and test the Mock Object. Then, my idea is to write a test on my MockTextBox that will check to be sure that the handler sets the cursor.

The Payoff?

Frankly, I expect the payoff on this exercise not to be in the test. After all, I already know that the code works. I expect to learn something about how to do Mock Objects in C#, and Im hoping that the refactoring will lead to some better ideas for how this part of the program should be done.

Well, enough chit-chat, lets get to work.

Extreme Programming Adventures in C#
Javaв„ў EE 5 Tutorial, The (3rd Edition)
ISBN: 735619492
EAN: 2147483647
Year: 2006
Pages: 291

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: