Testing main method by junit [duplicate]

夙愿已清 提交于 2019-12-01 02:14:59

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?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!