有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将单元测试嵌套在它测试的类中,而不是嵌套在另一个(外部)类中的目的是什么?

我一直在研究a particular open source library,其中所有单元测试都被定义为它们测试的类中的静态嵌套类,例如:

public class Foo {

    public int bar() { ... }

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

我以前从未见过这样做的项目或Java代码库,我真的很好奇它背后的想法

  • 与在另一个源文件夹src/test/java中使用单独的FooTest类相比,这种模式有什么优势吗

  • 这是使用Gradle作为构建工具的项目的惯例吗


共 (2) 个答案

  1. # 1 楼答案

    正如Jon Skeet所建议的,我找到了问题的答案within the documentation of the project

    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

  2. # 2 楼答案

    除了访问私有成员之外,将单元测试作为嵌套的内部类编写似乎没有任何优势。我能想到的缺点是:

    • 它使Java类变得非常庞大和笨拙
    • 最终的jar文件将包含测试代码,这在生产运行时可能是不必要的,并且通常不是一个好的实践(将生产代码与测试代码分开)

    另外,根据Java plugin的Gradle文档,它建议将测试保留在src/test/java中,因此我认为这根本不是一个特定于Gradle的约定