我在jMockit v 1.22中使用NonStrictExpectations
测试用例如下:
@Mocked Scanner mockScanner;
@Test
public void getNumber496() {
new NonStrictExpectations() {{
mockScanner.nextLine(); result = "496";
}};
int val = PrimeOrPerfect.getNumber(); // calls Scanner.nextLine() for a number
assertEquals(496, val);
}
模拟效果很好。
升级到jMockit v.1.25后,我改为Expectations
(因为NonStrictExceptions
已被弃用),如下所示:
@Mocked Scanner mockScanner;
@Test
public void getNumber496() {
new Expectations() {{
mockScanner.nextLine(); result = "496";
}};
int val = PrimeOrPerfect.getNumber(); // calls Scanner.nextLine() for a number
assertEquals(496, val);
}
模拟方法始终返回 null 。新代码出了什么问题?
以下是getNumber()的代码:
protected static int getNumber() {
logger.info(">>getNumber()");
Scanner scanner = new Scanner(System.in);
boolean validInput = false;
int number;
System.out.println("Enter a whole positive number (0 to quit):");
do {
String line = scanner.nextLine();
logger.info("input number: {}", line);
number = 0;
try {
number = Integer.parseInt(line);
} catch (NumberFormatException e) {
logger.debug("input is invalid: {}", e.toString());
System.err.println("Please enter a positive integer less than 1001.");
continue;
}
if (number < 0 || number > 1000 ) {
logger.debug("input is out of range 1..1000.");
System.err.println("Please enter a valid number between 1 and 1,000 inclusive.");
} else {
validInput = true;
}
} while (!validInput);
// Don't close the scanner because doing so also closes System.in. Do NOT uncomment the line below.
//scanner.close();
logger.info("<<getNumber()");
return number;
}