Question

I wanted to implement a testcase which will run particular java class and then, provide input to it and takes output from that.

So, there are three questions here:

1) How do we run another java class from junit? Do we need to run command line to do this? 2) After java class is run, how do we provide input to it? Do we print that on console? 3) How to read output of program, do we read console here?

I haven't written many test cases, written simple test cases which will call a method in any java class and asserts that. Can anyone help me in doing this?

Note: this is neither a college/school home work nor this is related to company work...... :p

Was it helpful?

Solution

1) Testing code written in another class from a junit test method involves either creating an instance of that class and then calling its methods, or calling static methods of the class. If you want to run that class's main method (the method that gets run automatically when you run your java program from the command line), then just call MyClass.main(someArgs), where someArgs is the fake commandline arguments given as an array of Strings.

2) After main is called your program will run like normal. You can enter your input manually to test your program if you want. But since you are writing test methods you probably want to automate this...

3) You can use System.setIn and System.setOut to redirect input and output to your own InputStream and OutputStream. Then you can send "user" input straight from your test method, and make assertions based on the content of the OutputStream.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top