Search code examples
javaunit-testingjunit

What is the purpose of nesting a unit test inside the class it tests, rather than in another (outside) class?


I've been looking through a particular open source library in which all unit tests are defined as static nested class inside the class they test, for example:

public class Foo {

    public int bar() { ... }

    public static class UnitTest {
        @Test
        public void testBar() { ... }
    }
}

I've never seen a project or Java codebase that does this before and I am really curious about the thinking behind it.

  • Is there any advantage over this pattern than having a separate FooTest class in another source folder src/test/java?

  • Is this a convention of projects that use Gradle as their build tool?


Solution

  • As Jon Skeet suggested, I found the answer within the documentation of the project in question:

    Hystrix has all of its unit tests as inner classes rather than in a separate /test/ folder.

    Why?

    • Low Friction
    • Context
    • Encapsulation
    • Refactoring
    • Self-documenting

    More information on the reasoning can be found in this blog post: JUnit Tests as Inner Classes