2

我有一个带有单个公共外观的包,有两种方法,启动和停止。因为这个外观适用于 50 多个内部/友好类包,所以我需要一种能够直接测试其中几个内部类的方法。

我正在使用 Eclipse 和 JUnit。

反射可能是一个好方法,但是为什么要自己编写所有这些反射代码,是否有生成包装器公共类的好工具(如 .net Visual Studio 可以)?

其次,有人可以解释一下如何为 JUnit 管理双源代码树,或者让我参考该主题的一篇好文章吗?我看过几篇博客文章,但更想看看这里的人是否有很好的解释/参考。

而且,最重要的是——是否测试内部类,这不是我的问题,这是我的设计,也是我喜欢的工作方式。有些人认为你应该,有些人认为你不应该,所以请不要发布答案,例如:你应该只测试公共,这样问题就解决了。我在stackoverflow中搜索并找不到关于它的好帖子。

先感谢您 ,

詹姆士 。

4

2 回答 2

1

据我了解 Louis Wasserman 的回复,您的文件结构看起来像

src/production/mypackage/MyClass.java

src/junit/mypackage/MyClassTest.java

然后 src/production/mypackage/MyClass.java 看起来像

class MyClass
{
      void start ( ) { ... }
      void stop ( ) { .... }

      class InnerClass1 { ... } 
      class InnerClass2 { ... }\
      ...
      class InnerClass50 { ... }
}

由于 MyClassTest 和 MyClass 在同一个包中 mypackage.MyClass.InnerClass1...50 可以从 MyClass 测试中进行测试。

确保 MyClass 不依赖 MyClassTest 做任何事情。对于生产,您可以编译生产目录中的所有内容(完全跳过 junit 测试)。为了测试编译两个目录。

于 2012-04-21T01:02:53.633 回答
1

Your instinct to maintain a dual source tree is correct. Simply have two source directories, with the same directory/package structure within. Compile to similarly separate output destinations, but put everything in your classpath when you run tests. Even though the classes may be even different output directories, their identical directory/package structure will make it work. If you use Maven, this is standard. With that tool, the source directory names are src/main and src/test, and the output directories are target/classes and target/test-classes. The fact that Maven supports this out of the box shows how standard this practice is within the Java community and you should use it with confidence. (For that matter, I encourage you to use Maven, it will make your life a lot easier. You can use Maven with Eclipse and lots of people do.)

With unit tests now being inside your package, you can test all the package-protected classes you want. I disagree with people who say only test public things. In fact, no less a luminary than Cedric Beust, the author of TestNG, argues that if it can break, it should be tested, and that includes private methods. I have unit tested private methods with a little help from reflection. Package-protected stuff is of course easier to test. Regardless, I think it's a religious argument to say that only public things should be tested.

于 2012-04-21T01:38:30.507 回答