Reputation: 1016
I'm trying to build a simple app, which has a switch/case statement as follows:
public void handleUserInput(char input){
switch(input) {
case 'L':
printBooksList();
break;
case 'Q':
System.exit(0);
default:
System.out.println("The option you chose was invalid");
}
}
I'm trying to do this TDD to learn some of the basics, with JUnit and Mockito. However I have absolutely no idea how to test a program has quit. I have to create an object of MyApp to then pass in a mocked InputStream with the value 'Q' quit, so somehow mocking doesn't fit. Even if this method was public, it's not exactly a method I can verify has been called through mocks.
Does anyone know any way on how to go about this?
I'm aware of this answer but I'm not testing a static method, and having another constructor to pass in a mocked out System seems overkill.
This is the test I have written taking answers from the question I linked to:
@Test
public void shouldCallSystemExit() {
inputStream = new ByteArrayInputStream("X".getBytes());
testSubject = new BibliotecaApp(inputStream);
PowerMockito.mockStatic(System.class);
testSubject.handleUserInput('Q');
PowerMockito.verifyStatic();
System.exit(0);
System.out.println("If this message displays them System.exit() was mocked successfully");
}
But this is throwing dependency issues left right and centre! I've had to download 5 jars for PowerMock to work and it's still asking for hamcrest/SelfDescribing. This can't be right, I'll be downloading everything at this rate.
Upvotes: 2
Views: 4878
Reputation: 328594
There are several ways to test System.exit()
in a JUnit test:
System.exit()
and overwrite this method in the test.The reason is that System.exit()
never returns, so control never returns to your test. So you have to make sure that the actual method isn't called.
Upvotes: 3