问题描述
我写了一个类,它从main方法中获取控制台和参数的输入。 main方法为不同的控制台输入调用不同的方法,并为不同的参数调用不同的函数。因此,我想通过模拟文件中的这些输入来使用Junit测试这个主要方法。我该怎么做?在junit中是否有任何特殊规定来测试类的主要方法?
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?
推荐答案
要提供文件的输入,请a FileInputStream
并将其设置为 System.in
流。您可能希望在main方法完成后将原始设置恢复,以确保以后使用它的任何东西仍可正常工作(其他测试,JUnit本身......)
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...)
下面是一个示例:
@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);
}
在您的实际代码中,您需要处理任何IOExceptions并使用更好的东西而不是文件的完整路径(通过类加载器获取),但这给了你一般的想法。
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.
这篇关于通过junit测试main方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!