Tagbangers Blog

Naming Test Methods

If you're a programmer, at some point you should have faced the struggle of coming up with a good name for your classes, methods, and variables.

You should have regretted looking back at your old code, thinking something like "how the hell did I come up with such a lame name?", or "I should've named it this way".

Somebody once said:

Naming is VITAL! Over half of your program is about naming!

I'm not sure if over half of your program is about naming, but I agree that naming is extremely important.

To tell you the truth, naming really comes down to your "sense of naming". In a company, however, it is important to have some kind of baseline conditions or rules in naming things. 

That is why lately I've been thinking of what kind of rule should we have for naming test methods for Junit.

@Test
public void ユーザが作成できる() {  // "Can create user"
    User user = new User();
    //・・・abbr.
}

@Test
public void 名前入力がない時はユーザが作成できない() {  //"Can't create user without name input"
    User user = new User();
    //・・・abbr.
}

In the past we've had methods with Japanese names like the ones above, but I think English names look way cooler.

And most importantly, many of the people who look at our service "Wallride" are not Japanese. 


I want the rules to be ASAP (as SIMPLE as possible), and the one that I have in mind right now is something like this:

Say were making a method for creating users like the ones above. In this case, we would have one "regular" method, and the others would be "irregular" methods.

@Test
public void createUser() {  // The "regular" method
    User user = new User();
    //・・・abbr.
}

@Test
public void createUserWithoutName() {  // The "irregular" method
    User user = new User();
    //・・・abbr.
}

@Test
public void createUserWithInvalidEmail() {  // The "irregular" method
    User user = new User();
    //・・・abbr.
}


Rules of Naming

  • The "regular" methods should be named the same as the method we're testing.
  • The "irregular" methods should be named with a combination of the name of the method we're testing and its conditions.


When we're dealing with methods that does something complex, it could be pretty hard to apply these rules. If that's the case, it might be a good opportunity for you to review the design itself.

When there's too many "irregular" methods, it might be better to just combine them all together into a single method, but who knows?


Original article written by: Tetsuya Shimauchi

Translated by: Yu Koga