Trust, but verify.

President Reagan, for all his faults, gave us a very useful aphorism in describing his approach to diplomacy with the Soviet Union: “Trust, but verify.” This is also a very useful approach to take when writing unit tests when you’re working with a framework, particularly when you’re developing a human interface.

For example, Cocoa uses the target-action pattern for controls. When you create an NSButton you can specify which object to send a message to when it’s clicked — the target — and what message to send — the action.

You can trust that when you click the button, Cocoa will cause the action message to be sent to the target object so long as they have been properly specified. Therefore you probably don’t need to write a unit test that simulates clicking on the button. However, you should verify that your button has had its target and action properly specified, and you can write a test for this.

You can also apply this principal in your own code. Let’s say you’re implementing a new type of control that also has to follow the target-action pattern. In the tests for your control itself, you probably will want to simulate the appropriate user-interface events and see that a testing instance of your control behaves appropriately. However, you don’t need to do this in the code that uses the control — you can trust that the control behaves correctly due to the tests you wrote for the control itself, and just verify that it’s been properly configured.

1 Comment

  1. Allan Odgaard
    May 25, 2010

    Ironically I am regularly searching for stuff about testing nibs/Cocoa because I don’t trust Cocoa 🙂

    For example I may work with NSTableView in a way where it matters to me when it sends me notifications about changing selection, when it reload items, etc. — sometimes the documentation does not make these things clear so (despite attempts of avoiding it) I end up with assertions in my code about how Cocoa acts. This behavior may be wrong in some edge case or it may subtlety change in an OS upgrade.

    So I very much want tests (and regression tests) for these things.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *