概述
I found really hard to write unit test for this method, it basically exits the program when user types a quit command.
SytemExit class:
public class SystemExit {
public void exit(int status) {
System.exit(status);
}
}
My static method:
public static void exitWhenQuitDetected() {
final SystemExit systemExit = new SystemExit();
final String QUIT = "quit";
String line = "";
try {
final InputStreamReader input = new InputStreamReader(System.in);
final BufferedReader in = new BufferedReader(input);
while (!(line.equals(QUIT))) {
line = in.readLine();
if (line.equals(QUIT)) {
System.out.println("You are now quiting the program");
systemExit.exit(1);
}
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
Something is not quite right here as I am struggling to unit test the method exitWhenQuitDetected (I am using Mockito for mocking). How would I mock the InputStreamReader and verify the SystemExit.exit method gets called when it sees a quit? Can you shed some lights on this please? Thanks.
Added the test I am working on at the moment, it's not working.
@Test
@Ignore
public void shouldExitProgramWhenTypeQuit() {
String quit = "quit";
SystemExit systemExit = mock(SystemExit.class);
try {
BufferedReader bufferedReader = mock(BufferedReader.class);
when(bufferedReader.readLine()).thenReturn(quit + "n");
SomeClass.exitWhenQuitDetected();
verify(systemExit, times(1)).exit(1);
} catch (IOException e) {
e.printStackTrace();
}
}
解决方案
You've done 90% of the work already, by placing the actual exiting code off in a separate class with no logic of its own. Your difficulty is caused by your use of a static method.
I would advise making the exitWhenQuitDetected not static. Put it in a class that you can instantiate when you need it, and that you can create with a mocked SystemExit. Something like this.
public class SomeClass{
private final SystemExit exiter;
private final static String QUIT = "quit";
public SomeClass(){
this(new SystemExit());
}
SomeClass(SystemExit exiter){
this.exiter = exiter;
}
public static void exitWhenQuitDetected() {
String line = "";
try {
final InputStreamReader input = new InputStreamReader(System.in);
final BufferedReader in = new BufferedReader(input);
while (!(line.equals(QUIT))) {
line = in.readLine();
if (line.equals(QUIT)) {
System.out.println("You are now quiting the program");
exiter.exit(1);
}
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
// ...
}
Then, in your test, you can make a mock of SystemExit, and use the package-private constructor of SomeClass to create an object that will use your mock as its exiter. You can then run your test, and verify on your mock SystemExit.
最后
以上就是怡然板栗为你收集整理的java退出控制台,Java编写单元测试,用于在控制台中退出用户类型时退出程序的全部内容,希望文章能够帮你解决java退出控制台,Java编写单元测试,用于在控制台中退出用户类型时退出程序所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复