@Test
	public void testCalculatorVisitor() {
		String input = "2 + 8 / 2";
		VisitorCalcLexer lexer = new VisitorCalcLexer(new ANTLRInputStream(input));
		VisitorCalcParser parser = new VisitorCalcParser(new CommonTokenStream(lexer));

		VisitorCalcParser.SContext context = parser.s();
		assertEquals("(s (expr (expr 2) + (expr (expr 8) / (expr 2))) <EOF>)", context.toStringTree(parser));

		VisitorCalcVisitor<Integer> listener = new VisitorCalcBaseVisitor<Integer>() {
			@Override
			public Integer visitS(VisitorCalcParser.SContext ctx) {
				return visit(ctx.expr());
			}

			@Override
			public Integer visitNumber(VisitorCalcParser.NumberContext ctx) {
				return Integer.valueOf(ctx.INT().getText());
			}

			@Override
			public Integer visitMultiply(VisitorCalcParser.MultiplyContext ctx) {
				Integer left = visit(ctx.expr(0));
				Integer right = visit(ctx.expr(1));
				if (ctx.MUL() != null) {
					return left * right;
				}
				else {
					return left / right;
				}
			}

			@Override
			public Integer visitAdd(VisitorCalcParser.AddContext ctx) {
				Integer left = visit(ctx.expr(0));
				Integer right = visit(ctx.expr(1));
				if (ctx.ADD() != null) {
					return left + right;
				}
				else {
					return left - right;
				}
			}

			@Override
			protected Integer defaultResult() {
				throw new RuntimeException("Should not be reachable");
			}

			@Override
			protected Integer aggregateResult(Integer aggregate, Integer nextResult) {
				throw new RuntimeException("Should not be reachable");
			}
		};

		int result = listener.visit(context);
		int expected = 6;
		assertEquals(expected, result);
	}
This test verifies that the visitor correctly dispatches calls for labeled outer alternatives.
runtime-testsuite/test/org/antlr/v4/test/runtime/java/api/TestVisitors.java