I’m trying to decide on a naming convention for unit tests. I like the one recommended by Roy Osherove:
[MethodName_StateUnderTest_ExpectedBehavior]
http://osherove.com/blog/2005/4/3/naming-standards-for-unit-tests.html
I’m not sure about this standard for the negative tests where we are testing if the application is handling wrong behavior correctly by throwing an exception.
So the ExpectedBehavior would in this case always be “CorrectExceptionThrown”. Would it still make sense to write the ExpectedBehavior for each negative unit test or is it ok to make it optional?
There are pros and cons. On one side it’s always the same for negative tests so it would be redundant to write it every time, it makes the unit test method name long. It’s also a risk that the expected behavior will not be added for unit test where it’s necessary, if we make it optional. I also think that it’s better to keep it consistent in the entire project so apply it the same way everywhere.
There’s nothing redundant in specifying what exception is thrown as operation result. This actually fits perfectly into Roy’s naming convention, given:
You get an important information about your code – type of exception thrown. However, when you have classical happy path test usefulness of some parts of name is subjective. Consider:
What information do such names carry? Rather little.
ReturnsResultessentially means it works.NothingSpecialHappensis also rather vague information. In such cases, dropping part of the name might be justified.Note however, instead it might be worth considering changing name rather than dropping part of it completely (for example,
ReturnsResultcould be replaced with less vagueReturnsEntityFromDatabaseorReturnsSerializedValue).Finally, don’t follow Roy blindly – treat it as guidelines, rather than conventions. Conventions rarely fit for all possible situations, and this one is no different.