6

I have read several posts which discuss coding standard for naming the unit test methods for improving readability.

I follow this NameOfMethod_ExpectedBehavior_WhenSomeScenario, but now I am confused as to how should I continue with this in the face of overloaded methods. There can be several methods with same name but different signatures.

Can someone please suggest me how to incorporate overloading in method names?

For example: Java Code

class ClassUnderTest{
    public int method1(){
    }

    public int method1(int arg){
    }
}

Now I need to test both the methods individually from my test case. I am thinking of some standard that is applicable for this scenario.

3 Answers 3

2

The overload being tested doesn't really matter. The state really handles the decision of which overload to call.

So if you have a ToString method on a DateTime object with one that takes no arguments and one that takes a format string you would have.

ToString_1-3-2014T00:00:00_JanThirdDefaultFormat

and

ToString_1-3-2014_JanThirdDateOnly
1

Since your test methods typically don't have different signatures (I guess they will seldom have parameters), you need a different way to distinguish them. As long as the WhenSomeScenario part is different for different overloads, you don't have to provide any special measures:

 MyMethod_Returns0_WhenCalledWith1     // testing MyMethod(int)
 MyMethod_Returns0_WhenCalledWith1_2   // testing MyMethod(int,int)

does it.

If that does not work in specific cases, because you have a more abstract scenarios to test, where the names don't reflect the input parameters directly, you need something like

  NameOfMethodSignaturecode_ExpectedBehavior_WhenSomeScenario

You still have to decide what you fill in for the Signaturecode, depends a little bit on your personal taste. When you are willing to use very long method names, you could use just add a concatenation of the typenames, like

 MyMethodInt_Returns0_WhenCalledBeforeInitialization     // testing MyMethod(int)
 MyMethodIntInt_Returns0_WhenCalledBeforeInitialization // testing MyMethod(int,int)

If you think the method names become too long that way, you have to use some kind of shortage for the typenames (for example, analogous to the shortages in Hungarian notation). What I would avoid is to use some kind of index 1,2,3,... to distinguish the test methods, this gives you no clue which test method is for which overload.

1

Methods typically require more than a single unit test. I have found GIVEN...WHEN...THEN naming to be superior in most cases. It's ok to have multiple tests that say GIVEN_...WHEN_overloaded_method_THEN...

The method names get rather long but it doesn't matter because they are never called explicitly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.