Alan Dean

CTO, Developer, Agile Practitioner

Photograph of Alan Dean

Saturday, November 12, 2011

Unit test naming convention

I have been using TDD since before it was even called that. The practice was called test-first at the time and I learnt to do it with ComUnit against VB6 code. I suspect that there aren't many people who can put down more than a decade of of TDD on their CV. Probably due to this, I employ somewhat idiosyncratic practices, such as a distinct interface focus (both the default interface and those additionally implemented). Accordingly, I have a fairly well elaborated naming convention for my unit tests in order to make test scenario coverage more rigorous and visible.

The overall convention is public void memberKind_parameterType_parameterType_whenScenarioInfo()

Member Kinds (when default or implicit interface implementation)

  • Constructors: ctor
  • Properties: prop
  • Indexers: index
  • Methods: op, opImplicit, opExplicit
  • Generic Methods: op_MethodNameOfT, op_MethodNameOfClass, op_MethodNameOfNew, op_MethodNameOfIInterfaceName

Member Kinds (when explicit interface implementation)

  • Properties: IInterfaceName_prop
  • Indexers: IInterfaceName_index
  • Methods: IInterfaceName_op

Special Names

  • Type definition assertions: a_definition
  • Assert deserialization: xmlDeserialize, jsonDeserialize
  • Assert serialization: xmlSerialize, jsonSerialize

Parameter Types

  • Keywords: int, string
  • Null types: stringNull, TypeNameNull
  • Empty string: stringEmpty
  • Invalid string: stringInvalid
  • Specific values: longZero, intOne, decimalNegative, floatEpsilon, shortMin, DateTimeNow

Used to disambiguate two or more tests which otherwise have the same name, e.g. op_ToString_whenDefault(), op_ToString_whenDescriptionIsNull()

Cavity has almost complete test coverage so there are plenty of examples. Here are some:


So obvious that I forgot to mention it, but worth putting on the record: each class should have exactly one test class, i.e. Example.cs has Example.Facts.cs (if xUnit) or Example.Tests.cs (if NUnit, MSTest, etc.). The period in Example.Facts or Example.Tests is to force the same sort order of units and tests in the Visual Studio solution explorer tree view. I use a pair of templates to assist me (installer available in downloads).

No comments: