我目前正在尝试对Junit进行Uni作业测试。下面是我尝试测试的一种方法的示例。
public static int choosePlayers(int num) {
while (validPlayerNumber == false) {
try {
System.out.print("Please enter Number of players (2-4)\n> ");
num = in.nextInt();
switch (num) {
case 2:
validPlayerNumber = true;
numberPlayers = num;
System.out.println(numberPlayers + " players selected");
break;
case 3:
validPlayerNumber = true;
numberPlayers = num;
System.out.println(numberPlayers + " players selected");
break;
case 4:
validPlayerNumber = true;
numberPlayers = num;
System.out.println(numberPlayers + " players selected");
break;
default:
throw new IllegalArgumentException("Sorry, that is not a valid selection.");
// System.out.println("Sorry, that is not a valid selection.");
}
} catch (InputMismatchException ex) {
// log the exception
System.out.println("Problem with input : " + ex.toString());
continue;
}
}
return numberPlayers;
}
我正在使用以下测试类对此进行测试:
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
num1 =1;
num2= 2;
num4 = 4;
num3 = 3;
num5 = 5;
game= new Game();
}
@Test
public void testchoosePlayers2() {
System.out.println("Testing choosingPlayers 2");
Scanner scanner = new Scanner (System.in);
int expected = scanner.nextInt();
int actual = game.choosePlayers(num2);
assertEquals(expected, actual);
System.out.println("Test finsihed");
}
@Test
public void testchoosePlayers3() {
System.out.println("Testing choosingPlayers 3");
Scanner scanner = new Scanner (System.in);
int expected = scanner.nextInt();
int actual = game.choosePlayers(num3);
assertEquals(expected, actual);
System.out.println("Test finsihed");
}
@Test
public void testchoosePlayers4() {
System.out.println("Testing choosingPlayers 4");
Scanner scanner = new Scanner (System.in);
int expected = scanner.nextInt();
int actual = game.choosePlayers(num4);
assertEquals(expected, actual);
System.out.println("Test finsihed");
}
每次我尝试运行此测试时,只会运行第一个测试,并且扫描仪不会为随后的第二次重新提示。是否有解决办法?对于此问题的任何建议,或者以更好/更有效的方式测试上述方法,我将不胜感激。
答案 0 :(得分:1)
这里的目的是测试方法是否使用提供的输入参数返回正确的值。如果扫描不正确,值测试将失败。因此,与其扫描期望值,不如将期望值放入断言中。另外,由于您测试了相同的功能,因此您无需在此处进行单独的测试。
要模拟输入,您需要用自己的输入流替换System.in。有关详细信息,请参见JUnit: How to simulate System.in testing?。
private final InputStream systemIn = System.in;
private ByteArrayInputStream testIn;
@After
public void resetSystemIn() {
System.setIn(systemIn);
}
private void inputData(String data) {
testIn = new ByteArrayInputStream(data.getBytes());
System.setIn(testIn);
}
@Test
public void testchoosePlayers() {
System.out.println("Testing choosingPlayers 2");
inputData("2");
int actual = game.choosePlayers(num2);
assertEquals(num2, actual);
System.out.println("Testing choosingPlayers 3");
inputData("3");
actual = game.choosePlayers(num3);
assertEquals(num3, actual);
System.out.println("Testing choosingPlayers 4");
inputData("4");
actual = game.choosePlayers(num4);
assertEquals(num4, actual);
System.out.println("Test finsihed");
}