您能帮我为下面的代码编写Junit测试用例吗?
public class ConsoleReader implements InputReader {
public Cell readInput() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the co-ordinate Seperated by Comma");
String coOrdinates = reader.readLine();
String[] values=coOrdinates.split("\\,");
return new Cell(Integer.parseInt(values[0]),Integer.parseInt(values[1]));
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
}
答案 0 :(得分:2)
将reader
提取为字段。 (您可以直接或在构造函数中对其进行初始化)
private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
定义吸气剂(public
或protected
)
protected BufferedReader getReader(){
return reader;
}
从您的方法中删除new BufferedReader(...)
的初始化。取而代之的是使用getReader()
。
public Cell readInput() {
try {
System.out.print("Enter the co-ordinate Seperated by Comma");
String coOrdinates = getReader().readLine();
String[] values=coOrdinates.split("\\,");
return new Cell(Integer.parseInt(values[0]),Integer.parseInt(values[1]));
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
在测试类中,将ConsoleReader
初始化为Mockito.spy
ConsoleReader consoleReader = spy(new ConsoleReader());
模拟您的吸气剂
@Before
public void setUp() {
BufferedReader bufferedReader = mock(BufferedReader.class);
doReturn(bufferedReader).when(consoleReader).getReader();
doCallRealMethod().when(consoleReader).readInput();
}
定义您的测试:
@Test
public void testReadInput() {
when(bufferedReader.readLine()).thenReturn("123,456");
Cell expectedCell = new Cell(123, 456);
Cell actualCell = consoleReader.readInput();
assertEquals(expectedCell, actualCell);
}
答案 1 :(得分:0)
您可以使用Mockito模拟BufferedReader,如下例所示。
BufferedReader bufferedReader = Mockito.mock(BufferedReader.class);
Mockito.when(bufferedReader.readLine()).thenReturn("1", "2", "3");
// You can mock the result based on the type of result you are expecting.