Testing grammars with JUnit

Philosophy

I have opted to use a more compositional object-oriented model rather than inheritance. To test a grammar, you will need to instantiate an ANTLR Tester object which will do most of the heavy lifting for you.

Also, this library uses a fluent interface (of sorts) to chain the processing through the various phases of your front end. I find this remarkably easy to read.

Error Handling in Grammars

As of version 0.8, in order for ANTLR Testing to detect when a grammar produces an error, you must print something to standard error (i.e., System.err). ANTLR uses standard error by default.

Those still using 0.7 or earlier should upgrade (or add this ugly code to their grammars).

Build a Front End

You need to provide an ANTLR Tester with a factory for your front end by implementing the org.norecess.antlr.IANTLRFrontEnd interface. This will require you to implement methods for

  • Producing a lexer.
  • Producing a parser.
  • Producing a tree parser.

If you do not use a tree parser, the method that should produce a tree parser can throw an exception or return null. Just don't try to tree parse off of the ANTLR Tester!

Build an ANTLR Tester

Initialization of an ANTLR Tester typically looks like this:

private ANTLRTester myTester;
@Before
public void setUp() {
  myTester = new ANTLRTester(new MyOwnFrontEnd());
}

where MyOwnFrontEnd is a class that implements IANTLRFrontEnd.

Write Tests!