Paul Gielens:ThoughtsService

another Endpoint to my thoughts

News

Syndication

Ads


Favorites

Projects

Naming Unit Test Pattern

I always have a hard time to come up with good names for my unit tests. Dale H. Emery found an article by Brian Button called "TDD Defeats Programmer's Block—Film at 11." In which Brian, according to Dale, uses a certain pattern for test names: stimulus and result in context. Dale examined the test names used in the article to identify the pattern parts.

In my recent article I used “Pay_IncludingSalesBonus” as name for a test. This test determined whether the correct pay amount was being calculated for an employee which was granted to receive a sales bonus. Due to the line length for printing (great excuse) I decided for a shorter version of the actual name. The actual name was (according to the stimulus and result in context pattern).

CalculatePayIncludingSalesBonusAfterSalesBonusGrantedToEmployee:

Context: Sales bonus granted to employee.
Stimulus: Calculate pay amount to pay employee.
Result: Pay amount was calculated including the sales bonus.

I think this pattern is extremely useful when used deliberately. To quote Dale:

Using the context-stimulus-result scheme increases the value of tests as documentation. The resulting names make clear what specifically is being tested and under what specific conditions. This helps the reader to understand quickly what each test does, and what is covered by each set of tests.

Another benefit is that the context-stimulus-result naming scheme encourages you to clarify your thinking about each test. Each unit test establishes some set of starting conditions, or context. Each stimulates the system. Each compares the result to a desired result. In order to name these elements you will have to think about the specifics of each and clarify them well enough that you can describe each in a few words.

If you're having difficulty naming a test using this scheme, that may indicate a problem in your test. Perhaps the test is doing too much work, or your test suite is doing too little. For example, suppose you're testing software to manage bank accounts, and one test is called Withdrawal Test. We can tell from this name that the test tests the withdrawal feature in some way. But we don't know what specific aspects of withdrawals this test is testing.

Is this useful, comments?

Comments

No Comments