Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Writing unittest for exiting a program when user type quit in the console

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();
    }       
}
like image 323
Can Lu Avatar asked Jan 28 '26 11:01

Can Lu


1 Answers

You should include the PowerMockito Jars into your project rather than just vanilla Mockito. The Powermock library is designed for mocking Static and/or Final classes and methods.

The following this blog post contains example code describing a similar scenario to yours.

Essentially you require a test class similar to this...

@RunWith(PowerMockRunner.class)
@PrepareForTest({System.class, ClassToTest.class})
public class SystemExitTest {

    @Test
    public void shouldCallSystemExit() {

        PowerMockito.mockStatic(System.class);

        ClassToTest.methodToTest();

        PowerMockito.verifyStatic();

        System.exit(0);

        System.out.println("If this message displays them System.exit() was mocked successfully");
    }    
}

Given this simple implementation class...

public class ClassToTest {

    public static void methodToTest() {
        // do some stuff
        System.exit(0);
    }
}
like image 108
Brad Avatar answered Jan 31 '26 00:01

Brad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!