我正在研究 ANTLR-Parser,现在正在为解析器编写测试。
我已经找到了一种“肯定”的方法——测试解析器,但现在还想测试解析器在输入错误时也会失败(否定测试?)。
我想要的是一种使用 JUnits 的方法Assertions.assertThrows(),例如NoViableAltException解析器抛出的一个或任何其他异常。
我已经查看了ANTLRErrorListener及其实现,但还没有找到解决方案。
到目前为止,这是我的测试用例:
@Test
public void test_short_negative() {
String[] string_values = new String[]{"{", "<EOF>"};
int[] id_values = new int[]{MyLexer.CBRACKET_OPEN, MyLexer.EOF};
ArrayList<TestToken> tokens = new ArrayList<>();
for (int i = 0; i < id_values.length; i++) tokens.add(new TestToken(string_values[i], id_values[i]));
ListTokenSource source = new ListTokenSource(tokens);
for(TestToken t: tokens) t.setTokenSource(source);
TestErrorListener errorListener = new TestErrorListener(true);
MyParser pars = createParser(new ListTokenSource(tokens), errorListener);
pars.stmt_block();
}
public class TestErrorListener extends BaseErrorListener {
private boolean hadError = false;
private TestToken lastOffendingSymbol;
private boolean doPrint;
public TestErrorListener(boolean doPrint){
this.doPrint = doPrint;
}
public boolean hadError() {
return hadError;
}
public TestToken getLastOffendingSymbol() {
return lastOffendingSymbol;
}
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
if(doPrint) System.out.println("Syntax error at " + line + ":" + charPositionInLine + ". Symbol: '" + ((TestToken) offendingSymbol).getText() + "' could not be parsed.");
hadError = true;
lastOffendingSymbol = (TestToken) offendingSymbol;
}
@Override
public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, boolean exact, BitSet ambigAlts, ATNConfigSet configs) {
if(doPrint) System.out.println("Ambiguity found at [" + startIndex + ":" + stopIndex + "]!");
}
}
UYOU
相关分类