I need to compile and run a java class from inside another java class, then input something into the console of the former.
The (console) output of the tested class needs to be redirected to the testing class.
I've already tried something similar where the tested file was given a text document instead of console input and had no problems there, which is why I think that the console input must be the problem.
Here's what I've come up with so far:
@testing
import java.io.*;
public class Test {
public static void main(String [] args) throws Exception{
Process javac = Runtime.getRuntime().exec("javac ToBeTested.java");
javac.waitFor();
Process process = Runtime.getRuntime().exec("java ToBeTested");
BufferedReader readFromProcess = new BufferedReader(new InputStreamReader(process.getInputStream ()));
BufferedReader errorFromProcess = new BufferedReader(new InputStreamReader(process.getErrorStream ()));
BufferedWriter writeToProcess = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
writeToProcess.write("Foo");
System.out.println("Foo written");
writeToProcess.write("FooBar");
System.out.println("FooBar written");
System.out.println("Tested Process:" +readFromProcess.readLine());
writeToProcess.write("Bar");
System.out.println("Bar written");
String line;
for (String line=readFromProcess.readLine(); line != null; line =readFromProcess.readLine()){
System.out.println("Tested Process:" +line);
}
process.waitFor();
}
}
@tested
import java.io.*;
public class ToBeTested {
public static void main(String[] args) throws IOException{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("foo");
System.out.println(input.readLine());
System.out.println("fooBar");
}
}
Right now the output is the following:
Foo written
FooBar written
Tested Process:null
Bar written
Also, if I comment out the line
writeToProcess.write("Bar");
the programm will get stuck in
process.waitFor();
,probably because ToBeTested still expects an input of some sort. Does this mean that the write methods work as intended? If so: Why doesn't the output work?
Please note that the ToBeTested class can't be changed (or even accessed for that matter). It would also be nice to get some sort of notification when an input is expected in ToBeTested, as the number and order of inputs required may vary.