我正在为java编程竞赛编写一些代码.程序的输入是使用stdin给出的,输出是在stdout上.你们如何测试在stdin/stdout上运行的程序?这就是我的想法:
由于System.in的类型为InputStream,而System.out的类型为PrintStream,因此我使用此原型在func中编写了我的代码:
void printAverage(InputStream in, PrintStream out)
Run Code Online (Sandbox Code Playgroud)
现在,我想用junit来测试它.我想使用String伪造System.in并在String中接收输出.
@Test
void testPrintAverage() {
String input="10 20 30";
String expectedOutput="20";
InputStream in = getInputStreamFromString(input);
PrintStream out = getPrintStreamForString();
printAverage(in, out);
assertEquals(expectedOutput, out.toString());
}
Run Code Online (Sandbox Code Playgroud)
实现getInputStreamFromString()和getPrintStreamForString()的"正确"方法是什么?
我这让它变得比它需要的更复杂吗?
我正在尝试为下面给出的函数编写Junit测试用例:
class A{
int i;
void set()
{
Scanner in=new Scanner(System.in);
i=in.nextInt();
}
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是当我为它创建一个Junit测试用例时,除了用户的输入之外它没有:
public void testSet() throws FileNotFoundException {
System.out.println("set");
A instance = new A();
int i=1;
instance.set(i);
// TODO review the generated test code and remove the default call to fail.
//fail("The test case is a prototype.");
}
Run Code Online (Sandbox Code Playgroud)
请建议我该怎么做才能接受用户的意见.
我想通过使用一些输入来对我的P2P系统进行一些测试:"join 8".8是节点号.对于我的系统,从stdin读取命令"join 8",但我不想为百次测试输入百次,所以我编写了一个测试函数来随机生成节点编号,然后调用"join"命令本身.所以我希望JAVA编写命令而不是我自己的输入到stdin.我怎样才能做到这一点?目标是:当我输入"test join 3"时,代码应该在1-255之间随机生成3个节点号,并为它们调用join命令.我的代码现在不能正常工作:
if (command[0].equals("test")) {
//test join
if (command[1].equals("join")) {
int nodenum = Integer.parseInt(command[2]);
Random rand = new Random();
Set<Integer> generated = new LinkedHashSet<Integer>();
while (generated.size() < nodenum) {
Integer next = rand.nextInt(255) + 1;
generated.add(next);
ProcessBuilder builder = new ProcessBuilder("java", "Test");
Process process = builder.start();
//stdIn=new BufferedReader(new InputStreamReader("join"));
OutputStream stdin = process.getOutputStream();
InputStream stdout = process.getInputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
writer.write("join "+next);
writer.flush();
writer.close();
}
}
}
Run Code Online (Sandbox Code Playgroud)