7

How can I specify human readable names of tests (to be shown in IDE and test reports) with JUnit 4?

Ideally by automatically converting actual test name.

Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72
ps-aux
  • 11,627
  • 25
  • 81
  • 128
  • 1
    Possible duplicate of [Changing names of parameterized tests](https://stackoverflow.com/questions/650894/changing-names-of-parameterized-tests) – achAmháin Jan 30 '18 at 07:47
  • You can use kotlin, which allows naming methods ``should do this``. Or you can use JUnit 5. – JB Nizet Jan 30 '18 at 07:48
  • I think you can't do better than camel case names and_or underscores – Mark Jeronimus Jan 30 '18 at 08:15
  • I would suggest that you just use programmer-readable identifiers for your test classes and test methods. (Seriously ... programmers are human!) – Stephen C Jan 30 '18 at 09:50

1 Answers1

8

I suppose that "human readable names" primarily means test names with spaces.

Underscores

My favorite solution for this problem is using underscores instead of spaces. This is the only solution that works together with IDEs nicely. E.g. you can jump from the test execution panel to the test with a single mouse click.

@Test
public void the_server_accepts_connections_with_password() {
    ...
}

Have a look at FakeSftpServerRuleTest for a complete test class that uses this style.

Test Runners

There are other solutions, but all of them require you to write an own Runner.

You can build a Runner that supports something similar to JUnit Jupiter's @DisplayName annotation.

You can build a Runner that converts the underscores from the test method's name to spaces for the display name of the test.

The problem with these solutions is that the IDE can no longer associate test results with the test method.

Non-standard Spaces

Warning: Don't do it!

Just for completeness. There are various space characters in Unicode and some of them can be part of method names in Java. You can write test names using them. You still have proper IDE support. Nevertheless: don't do it. The reader of the code will not realise that magic and become desperate.

Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72