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 http://www.pragmaticprogrammer.com/articles/may_02_mock.pdf .
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:
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.)
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.
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.