Unit Testing – Coding Standards for Unit Tests

coding-standardsunit testing

Usually when talking about coding standards we refer to the code of the program itself, but what about the unit tests? Are there certain coding standards guidelines that are unique to unit tests? What are they?

Best Answer

Off the top of my head, I can think of three differences in coding style for test code.

In naming test methods, I follow the pattern of shouldDoSomethingWhenSomeConditionHolds.

Inside the test, it is customary to follow the following spacing pattern:

@Test
shouldReturnAccountBalenceWhenGetBalenceIsCalled() {
    // Some lines 
    // of setup code
    // go here.

    // The action being tested happens after a blank line.

    // An assertion follows another blank line.
}

Some insist on only one assertion per test, but this is far from universal.

The DRY (Don't Repeat Yourself) is less of a consideration in test code than in production code. While some repeated code should be placed in a setUp method or a testUtils class, striving for zero repetition in test code will lead to tightly coupled and inflexible tests, which discourages refactoring.

Related Topic