使用Junit时源代码和测试代码的组织

王朝java/jsp·作者佚名  2006-01-31
宽屏版  字体: |||超大  

近来在学习使用 Junit test framwork .关于源代码和测试代码的组织问题我看了一些资料。其中有这样的建议:

1. Create test cases in the same package as the code under test. For example, the com.mydotcom.ecommerce package would contain all the application-level classes as well as the test cases for those components.

2.To avoid combining application and testing code in your source directories, create a mirrored directory structure aligned with the package structure that contains the test code.

(http://www.clarkware.com/articles/JUnitPrimer.html)

就是说测试代码应该被测试代码放在同一个package中,但是测试代码放在一个独立的目录中.也就是组织成下面这样:

1. esrc

2. com

3. s xyz

4. HelloWorld.java

5. test

6. com

7. xyz

HelloWorldTest.java

这样是比较合理。这样既可以方便地测试protected方法/域,同时不会导致源代码和测试代码混在一起,难于管理。

如果使用的是Eclipse,只需简单设置一下就可以了。

project -> properties -> Source标签 addFolder 按钮。

或者直接在classpath文件中直接设置也可以。将

<classpathentry kind="src" path=" "/> 换成:

<classpathentry kind="src" path="src"/>

<classpathentry kind="src" path="test"/>

即可。

如果使用命令行的方式,就要对编译和运行带有 package语句的java 文件有一定的了解。首先建立上述文件结构,编写java源文件。其中第一个语句就是

package com.xyz;

编译HelloWorldTest.java 的时候要这样:

g:\test > javac –cp “../src; .” com/xyz/HelloWorldTest.java

运行则是:

g:\test > java –cp “../src; .” com.xyz.HelloWorldTest

其中的关键就是要设置好classpath。至于为什么要这样,网上资料非常多,这里就不再赘述了。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有