Search code examples
javajunitjunit4assertinfinitest

Firing function on assert failure


I am working on complicated code generation using CodeModel available in Java. I have managed to setup my unit tests in such a way so that a test generates small but functionally complete Java code which gets compiled in memory and generated class(es) is/are loaded from memory. Everything in general is reasonably quick if I don't output generated code.

Since the generator code is not aware of generated classes, I use reflection to fire methods on generated class which works well. These methods also can fail as I use reflection to make sure methods did expected work by checking state of the object.

My problem is I don't want to log the generated code every time test is run. But I want to see the generated code if test fails. There are lot of tests and since I use infintest, my eclipse becomes slower as infinitest keeps accumulating the output from various tests.

Can I set up junit so that it calls my function if test fails? e.g.

boolean compileSuccessful = compile();
Assert.assertTrue("Ooops, you generated bad code", compileSuccessful);

If above assertion fails, I want to ouput generated code and see what went wrong.


Solution

  • You can use a TestRule, that adds the generated code to the output of failing tests. I suggest to extend TestWatcher.

    public class GeneratedCodeLogger extends TestWatcher {
      private Logger log;
    
      public GeneratedCodeLogger(Logger log) {
        this.log = log;
      }
    
      @Override
      protected void failed(Description d) {
        System.out.println(log.toString());
      }
    }
    

    Your test has to use this rule and log the generated code to the logger.