您的位置:首页 > 编程语言

使用Junit时源代码和测试代码的组织(摘自Daping_Zhang 的 Blog )

2005-06-21 17:16 537 查看
近来在学习使用 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。至于为什么要这样,网上资料非常多,这里就不再赘述了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: