2

As I read from Art of unit test, knowing that .NET can hide seam methods for testing in production runtime. (p.78~p.80). Such as,

public class LogAnalyzer
{
...
internal LogAnalyzer (IExtensionManager extentionMgr)
{
manager = extentionMgr;
}
}

run like this.

using System.Runtime.CompilerServices;
[assembly:
InternalsVisibleTo("AOUT.CH3.Logan.Tests")]

So LogAnalyzer() can only be called for test classes, without worries of adding extra cost on production code on purpose of testability. After brief survey, seems Java does not have equivalent feature. But does Java have alternatives? Thanks.

Jim Horng
  • 1,587
  • 1
  • 13
  • 23

2 Answers2

1

What about implementing your own custom ClassLoader? You can define your own annotation like @HideFromProductionCode and have your custom ClassLoader throw an exception if it loads a class that has the @HideFromProductionCode annotation. See How to set my custom class loader to be the default?

Alternately, just add a script to your build process that goes through all your compiled production code and looks for the @HideFromProductionCode annotation.

Community
  • 1
  • 1
Jack Edmonds
  • 31,931
  • 18
  • 65
  • 77
0

One fairly straightforward approach would be to use a Maven-like directory structure, with separate directories for production code and test code (typically under directories called src/main and src/test). When unit tests are run, the classpath includes both the main directory and the test directory. But when you build the JAR that gets deployed in production, only classes defined in the main directory are included; this way, production code that references test classes will result in a compile error.

Alex
  • 13,811
  • 1
  • 37
  • 50
  • Thanks for the answer. I was meaning in order to make production code test-able, we need to open up "seam" method for unit test to inject controllable stub/mock/derived class, my question is that how to hide these "seam" method which is only be called for test, not for production use. – Jim Horng Jul 25 '12 at 00:54
  • @JimHorng OK, I misunderstood the question. In that case, I would leave those methods and enable/disable them with some sort of configuration flag set a run-time (properties file, system property, etc). Having those methods present but disabled could be very useful for debugging problems that occur in a deployed production system. – Alex Jul 25 '12 at 15:36