views:

149

answers:

5

I'm new to unit testing using nunit (and Java development in general). When creating unit tests for private methods on classes, it looks as though the test file must be in the same package as the class being tested. What is the typical way of avoiding exporting the APIs of the unit tests? Can I make the classes/test methods package-protected? Or do developers typically have a separate build for release that excludes unit test files?

+1  A: 

I can tell IntelliJ or Ant not to package JUnit tests in the deployment. I have tests in a separate directory from the source code, which is what makes it possible.

Don't mingle source and test classes together. Keep them separate to make it easier for the tool/script you use to deploy.

duffymo
A: 

The test file does not necessarily have to be in the same package as the class being tested. In fact, it is a good practice to have the test files in a completely separate package, allowing them to test the public API without being concerned with package-level implementation details.

Alternately, you can set up your build script (e.g. Nant) to ignore files containing "Test" when you build your release executable.

Brett Daniel
A: 

Personally my approach is only to test exposed functionality, so you end up testing well encapsulated parts only.

This usually leads my design to contain small classes with well defined functionality, which are easier to test.

Generally, when unit testing you shouldn't be concerned with the internals of what you're testing, so I find this is the best way to approach it.

I also agree it's best to seperate test and production code.

RSlaughter
A: 

Keep test source code out of application source code. In general, only test exposed functionality. If you really need to test private behavior, create a test object that extends the real object and allows publec access to the private behavior.

tmeisenh
A: 

I think it's a mistake to move your test code out of the package of the CUT (Class Under Test). At some point you may want to test a protected method or class, and having your test code in another package makes that hard or impossible.

A better solution is to create a separate directory for your test code that simply mirrors the package structure of your production code. Here's what I do:

src/main/java/com/example/Foo.java
src/test/java/com/example/FooTest.java

Then your build script can very simply ignore src/test/** when it comes time for packaging and deployment.

Limbic System