Question

I have quite shallow understanding of JUnit and Javassist, i just want to use them to do some program analysis. For example given a library, I want to know during the runtime what methods in the library have been invoked. I can use bytecode manipulation to insert a system.out.println("method_name"); statement in the beginning of a method. So during the runtime, it will print out what methods have been invoked.

In standalone application i can intercept before the main() is called and use my own class loader(see below), however in JUnit there is no main(), could anyone show me how to intercept at this situation? Many thanks.

...
  Loader loader = new Loader( pool );
  loader.addTranslator( pool, xlat );
  loader.run( className, args );
...

Edit: I use JUnit 4.8 and Javassist 3.15.0.GA

Was it helpful?

Solution

Might I recommend an alternative approach instead? You can use an aspect-oriented approach instead, using AspectJ. With that, you can define pointcuts around a subset of or all methods that you want to monitor.

Another option is, if you're looking to monitor code coverage (the fact that you're using JUnit and just looking to do System.out.println(...) are good hints of this), maybe you're looking for a code coverage tool? If so, Cobertura would be your best bet - with no custom coding required.

Both of these options do their own byte-code manipulation, but without being something that needs to be maintained by the developer.

If you're using Eclipse as your IDE, both of these tie-in very nicely to Eclipse. AspectJ is actually an Eclipse project, but doesn't require Eclipse. The Eclipse plug-in for Cobertura is eCobertura.

Yet another option for this is to do it within JUnit itself - and this wouldn't require any bytecode manipulation. Take a look at its TestWatchman class. I don't yet have this documented online as I do with my other libraries, but you could take a look at my BaseTest class as part of my JUnit utilities library. Any JUnit test class that extends this will automatically log (to SLF4J) when each test starts, succeeds, or fails. However, this is all at a test-level only, and won't help monitor other methods that each test runs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top