When building a suite of unit tests for Java code, is there a convention for where to place test code in relation to source code?
For example, if I have a directory /java
that contains a bunch of .java
source files, is it better to put the test cases in /java
itself or use something like /java/test
.
If the latter is preferred, how do you test the internals of the code when the private
/protected
members of a class aren't available outside the package?
Java testing provides thorough and functioning test cases that can test every aspect of your application. A JUnit test case is exactly what it sounds like: a test scenario measuring functionality across a set of actions or conditions to verify the expected result. JUnit is a simple framework to write repeatable tests.
The developers should write unit tests alongside the source code and execute them in pipelines. Separating the repositories keeps more clean environment.
test should be in the src folder.
I recommend following the Apache Software Foundation's standard directory structure, which yields this:
module/ src/ main/ java/ test/ java/
This keeps tests separate from source, but at the same level in the directory structure. If you read through how Apache defines their structure, you'll see it helps partition other concerns out as well, including resources, config files, other languages, etc.
This structure also allows unit tests to test package and protected level methods of the units under test, assuming you place your test cases in the same package as what they test. Regarding testing private methods - I would not bother. Something else, either public, package, or protected calls them and you should be able to get full test coverage testing those things.
By the way, the link above is to Maven, Apache's standard build tool. Every Java project they have conforms to this standard, as well as every project I have encountered that is built with Maven.
You can put the tests in the same package as the original classes, even if the source code is under its own directory root:
PROJECT_ROOT +--- src/ +----test/
You can declare a class com.foo.MyClass
under src
and its test com.foo.MyClassTest
under test
.
As for access to private members, you can use reflection to invoke the methods (altering their accessibility via Class.getDeclaredMethod.setAccessible
), or you could use something like testng/junit5 to put some annotation-driven tests on the source code itself (I personally think this is a bad idea).
Why not check out some projects on java.net
to see how they've organized things, for example swinglabs (the SVN repository is pretty slow I'm afraid)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With