2つの数字を入力し、キーボード入力をクリアしてから再度チェックすると、それらがintかどうかをチェックするコードを記述しました。これは、JUnitテストでNoSuchElementExceptionを取得しますが、特定の入力値(5ではなく0)でのみ取得されます。JunitテストではNoSuchElementExceptionが返されますが、特定の数字のみが返されます
import java.util.Scanner;
public class HasException {
public int chooseNumber()
{
System.out.println("Enter a number, you can select 1 to 3");
int number;
do{
Scanner in=new Scanner(System.in);
while (!in.hasNextInt()) // when there isn't a integer next in the keyboard input
{
System.out.println("Not a number, please try again");
String discardedString = in.next(); // empty the buffer
}
number =in.nextInt();
if((number<1)||(number>3))
{
System.out.println("This is wrong choice, Please select 1 to 3");
}
}while((number<1)||(number>3));
return number;
}
}
import static org.junit.Assert.*;
import java.io.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class HasExceptionTest {
public final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
public final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
HasException myHasException; // declare the class to be tested
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() {
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
myHasException = new HasException();
}
@After
public void cleanUpStreams() {
System.setOut(null);
System.setErr(null);
}
@Test
public void test1() { // this test fails with NoSuchElementException
String input = "5" + "2";
InputStream in = new ByteArrayInputStream(input.getBytes());
System.setIn(in);
int result = myHasException.chooseNumber(); // exception NoSuchElementException here
assertEquals(result, 2);
}
@Test
public void test2() { // this test passes
String input = "0" + "2";
InputStream in = new ByteArrayInputStream(input.getBytes());
System.setIn(in);
int result = myHasException.chooseNumber();
assertEquals(result, 2);
}
}
ヒント:あなたの名前のスキルに見えます。 'HasException'はこのクラスの本当に悪い名前です。このクラスは、ユーザーに特定の入力を要求します。それには例外はありません。 ** ** **何かを意味する名前を使用してください。それを超えて:**あなたが**スキャナをこのメソッドに渡すとき。 System.inにScanner ** fixed **を作成する代わりに、複雑なセットアップをすべて行う必要はありません。そして、あなたのコードはもう少し再利用しやすくなります。 – GhostCat