简体   繁体   中英

jUnit Testing: Trying to write a test where I can input empty string to the function and I want to assert that the return value is null

Trying to write a test where I can input empty string to the function and I want to assert that the return value is null. Attached is my code snippet I am using:

    public String getUserInputNess() {
        String inputLine = null;
        try {
            BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
            inputLine = is.readLine();
            if (inputLine.length() == 0)
                return null;
        } catch (IOException e) {
            System.out.println("IOException: " + e);
        }
        return inputLine.toLowerCase();
    }

And below is my Unit test setup:

    private void provideInput(String data) {
        testIn = new ByteArrayInputStream(data.getBytes());
        System.setIn(testIn);
    }

    private String getOutput() {
        return testOut.toString();
    }

    @After
    public void restoreSystemInputOutput() {
        System.setIn(systemIn);
        System.setOut(systemOut);
    }

    @Test
    public void testGetUserInput() {
        /*
        Testing the getUserInput method by passing a user input and checking
        if it is returned
         */
        final String testString = "";
        provideInput(testString);
        GameHelper game = new GameHelper();
        String output = game.getUserInput("");
        assertNull(output);
    }

Thanks for your help and time in advance

The problem here is that static access hides dependencies .

Your code under test (cut) uses System.in as a dependency . The proper way to deal with that would be to inject this dependency into your cut. The way I suggest is to do this via a constructor parameter . The constructor then assigns it to a final member variable .

If you do so you can at test time pass a test double into your cut instead of the real dependency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM