我想节省一些时间,而不是手动测试解析文件中的每个标记,但似乎我不知道如何正确使用类的skip(String)
方法java.util.Scanner
。
换个说法:我如何使下面的两个测试都通过?
import java.io.StringReader;
import java.util.Scanner;
import junit.framework.Assert;
import org.junit.Test;
public class ScannerTest {
static private final String text = "FUNCTION_BLOCK Unnamed_project\n\tVAR_INPUT\n\t\tUnnamed_variable1 : REAL;\n\tEND_VAR\nEND_FUNCTION_BLOCK";
@Test
public void scannerSkipTest() {
Scanner sc = new Scanner(new StringReader(text));
sc.skip("(?i)FUNCTION_BLOCK");
String blockName = sc.next();
assert sc.hasNext("(?i)VAR_INPUT"); // added test
sc.skip("(?i)VAR_INPUT"); // line of failure
String variableName = sc.next();
sc.skip(":");
String type = sc.next();
sc.skip("(?i)END_VAR");
sc.skip("(?i)END_FUNCTION_BLOCK");
assert "Unnamed_project".equals(blockName);
assert "Unnamed_variable1".equals(variableName);
assert "REAL".equals(type);
}
@Test
public void scannerWithoutSkipTest() {
Scanner sc = new Scanner(new StringReader(text));
String skipped = sc.next();
assert "FUNCTION_BLOCK".equalsIgnoreCase(skipped);
String blockName = sc.next();
skipped = sc.next();
assert "VAR_INPUT".equalsIgnoreCase(skipped);
String variableName = sc.next();
skipped = sc.next();
assert ":".equalsIgnoreCase(skipped);
String type = sc.next();
skipped = sc.next();
assert "END_VAR".equalsIgnoreCase(skipped);
skipped = sc.next();
assert "END_FUNCTION_BLOCK".equalsIgnoreCase(skipped);
assert "Unnamed_project".equals(blockName);
assert "Unnamed_variable1".equals(variableName);
assert "REAL".equals(type);
}
}
任何提示和提示表示赞赏。