matt b
matt b

Reputation: 139921

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.

Upvotes: 1

Views: 1193

Answers (2)

matt b
matt b

Reputation: 139921

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

Upvotes: 6

will vuong
will vuong

Reputation: 166

There doesn't seem to be any advantage writing unit tests as a nested inner class besides access to private members. The disadvantages that I can think of are:

  • It makes your Java classes pretty honking big and unwieldy.
  • The final jar file will have testing code in it which is probably unnecessary during production runtime and is generally not a good practice (keeping production code separate from test code).

Also, according to the Gradle docs for the Java plugin, it recommends keeping tests in src/test/java so I don't think that this is a Gradle-specific convention at all.

Upvotes: 3

Related Questions