Java Unit Naming Convention

What naming conventions should I use for test classes and test methods?

Convention for TestSuite classes

As described in OrganizeJavaUnitTests, you should define one TestSuite class per package. Name the TestSuite class after the package being tested, following the template "<package name>TestSuite".

Convention for TestCase classes

As each class has its own test class, name the TestCase class after the class being tested, following the template "<class name>Test".

Convention for test methods

Following the rule "Test what you mean, not what you do", methods' names should tell what the test is doing and not which method it tests. You are testing the behaviour of a class, not simply a method. If you want to see what happens in an object if ThereIsNoSpoon, the test for the method DoSomething? should be testDoSomethingNoSpoon().

That said, each meaningful thing your class does should be encapsulated within one method. Thus, whilst your test is likely to have several method invocations in it, only one of them is likely to be the key method. Including the name of that method in your test method's name aids organizing your test methods, which in turn aids refactoring.

It is more important to test scenarios than methods; therefore, consider organizing your tests according to scenarios and not methods. As an example, if your class wraps a collection of objects, your tests can be organized by empty collection, single-element collection, multi-element collection, whether the collection contains duplicates and so on. In this case, the name of your test method corresponds to the scenario, and not the method. The reason is that your tests will likely make assertions on methods called contains(), size(), equals(), each(), collect(), reject() and so on... That said, I suggest using names that match scenarios. The scenario-based testing strategy should probably be described somewhere else. Sorry for the clutter. -- JbRainsberger


Contributor: RobertWatkins, VladimirBossicard, JbRainsberger


TestMethodNames?

We initially used to name out tests on the methods that we expected to test. And we found that they are pretty fragile and tend to get out of tune with the actual method as they get refactored etc. We have been using the AgileDox naming convention for our project and have found that it helps a lot to the readability of the test (using the TestDox? Idea plugin). Ensure the following:


EditText of this page (last edited July 21, 2008) or FindPage with title or text search