This question already has an answer here:
I wrote a class which takes input from console and arguments in main method. The main method calls different methods for different console inputs and it calls different function for different arguments. So i want to test this main method with Junit by mimicking these inputs from a file. how can i do it? Is there any special provision in junit to test the main method of the class?
To provide the input from a file, make a FileInputStream
and set that as the System.in
stream. You'll probably want to set the original back after the main method has finished to make sure anything using it later still works (other tests, JUnit itself...)
Here's an example:
@Test
public void testMain() throws IOException {
System.out.println("main");
String[] args = null;
final InputStream original = System.in;
final FileInputStream fips = new FileInputStream(new File("[path_to_file]"));
System.setIn(fips);
Main.main(args);
System.setIn(original);
}
In your actual code you'll want to handle any IOExceptions and use something better than a full path to the file (get it via the classloader), but this gives you the general idea.
IMO the best way to test the main method is by having the main method do absolutely nothing but set up the world and kick it off. This way one simple integration test gives the answer "has the world been set up".
Then all the other questions become much easier to answer.
The main method calls different methods for different console inputs and it calls different function for different arguments.
It should not, it should call someService.somemethod(args)
. This service gets tested like any other.
So i want to test this main method with Junit by mimicking these inputs from a file. how can i do it?
Either some form of fakes injected in or the use of the TemporaryFolder JUnit rule.
You can call main method from junit test like this:
YourClass.main(new String[] {"arg1", "arg2", "arg3"});
But since main method is void and does not return anything, you should test object that changed after main invocation;
Here is Link How do I test a method that doesn't return anything?
来源:https://stackoverflow.com/questions/36349827/testing-main-method-by-junit