As I'm currently adding more unit test to our code, I'm stuck because of a simple problem.
I need to write some boilerplate code to make it easy to write test classes. For example, to connect to the database without the configuration of the Resin server, using JNDI injection.
My problem is: where can I put boilerplate code that is only related to tests? Of course, it needs to be in my test directory, but is it good practice to create a package, call it "tool", in my package tree, as this package will have no equivalent in the package tree of the project source? Why or why not?
Edit:
Let's take an example: I need to create a class to inject a database connection into my test classes. Let's call it JNDIDatabaseInjector. This class will obviously only be used for test purposes, as the database connection used in production is defined in the application server configuration. In which package should I best put my JNDIDatabaseInjector 开发者_开发百科class?
This is the structure I would recommend for maven based projects:
.
|-- src/
| |-- main/
| | `-- java/
| | `-- com/
| | `-- example/
| | |-- bar/
| | | `-- Bar.java
| | `-- foo/
| | `-- Foo.java
| `-- test/
| |-- java/
| | `-- com/
| | `-- example/
| | |-- bar/
| | | `-- BarTest.java
| | |-- foo/
| | | `-- FooTest.java
| | |-- util/
| | | `-- Util1.java
| | |-- AbstractTest.java
| | `-- Util2.java
| `-- resources/
| `-- com/
| `-- example/
| |-- bar/
| | `-- BarTest-context.xml
| `-- foo/
| `-- FooTest-context.xml
`-- pom.xml
As you can see I put Util1.java
in util
subdirectory, but IMHO first common parent package (com.example
in this case) is a better choice. I would also advise you creating base abstract AbstractTest
class along with utilities to share common testing boilerplate.
Also note where I put testing resources (Spring context configuration in this example). This way you can access some test data (XML, SQL, etc.) easily just by issuing:
getClass().getResource("someFile.txt")
If you are in com.example.foo.FooTest
, the statement above will load file from src/test/resources/com/example/foo/someFile.txt
automatically.
This directory layout prevents from sibling dependencies between packages (only child -> parent or parent -> child). Don't know why, but somehow it feels better. The real problem comes when you want to share testing utilities between maven artifacts - one of the biggest flaws of maven's convention-over-configuration approach.
I put all of my for-release packages in a src Source Folder (in Eclipse). All of the junits go in the test-src Source Folder. This makes it simple to separate the test code and release only the packages that are to be released.
So it might look like this:
MyProject
- src
+ com.mycompany.tool
- test-src
- com.mycompany.tool
TestBed.java
As you are setting up, you might want to look into mockito to create your boilerplates.
精彩评论