Search code examples
javaunit-testingtestingantlrantlr4

ANTLR4 Visitor testing


I have described the grammar, it works fine. Now I'm at the point where I need to write unit tests for it. Does anyone know how to do this properly? I am using Java.
And how can I test the visitor with small programs that he will visit? Suppose I want to put some files in the resource directory, read the source code of the program from there and get the results for testing.

Could you give me a small example of how I can test this. For example, I have this method:

    @Override
    public Atom visitInt(final ProgramParser.IntContext ctx) {
        return new Value(Integer.parseInt(ctx.INT().getText()));
    }

Solution

  • Let's say your grammar looks like this:

    grammar Program;
    
    parse
     : int EOF
     ;
    
    int
     : Int
     ;
    
    Int
     : [0-9]+
     ;
    

    And your visitor like this:

    public class DemoVisitor extends ProgramBaseVisitor<Atom> {
    
        @Override
        public Atom visitInt(ProgramParser.IntContext ctx) {
            return new Atom(ctx.Int().getText());
        }
    }
    
    class Atom {
    
        public final String value;
    
        public Atom(String value) {
            this.value = value;
        }
    }
    

    then this can be tested like:

    @Test
    public void visitorTest() {
    
        ProgramLexer lexer = new ProgramLexer(CharStreams.fromString("42"));
        ProgramParser parser = new ProgramParser(new CommonTokenStream(lexer));
    
        Atom atom = new DemoVisitor().visit(parser.int_());
    
        Assert.assertEquals("42", atom.value);
    }