Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Osherove's naming convention for negative unit tests?

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.

like image 545
TheFitGeekGirl Avatar asked Feb 19 '23 13:02

TheFitGeekGirl


1 Answers

There's nothing redundant in specifying what exception is thrown as operation result. This actually fits perfectly into Roy's naming convention, given:

SomeMethod_ExpectionalState_ThrowsInvalidOperationException
SomeMethod_ExceptionalState_ThrowsArgumentNullException

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:

SomeMethod_DependencyReturnsCorrectResult_ReturnsResult
SomeMethod_WhenNothingSpecialHappens_ReturnsResult
SomeMethod_EverythingElseWorked_WorksToo

What information do such names carry? Rather little. ReturnsResult essentially means it works. NothingSpecialHappens is 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, ReturnsResult could be replaced with less vague ReturnsEntityFromDatabase or ReturnsSerializedValue).

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.

like image 111
k.m Avatar answered Feb 28 '23 11:02

k.m