Testing console based applications/programs - Java

前端 未结 5 1463
故里飘歌
故里飘歌 2020-12-03 05:47

All,

I have written a PhoneBook application in Java that is command line based. The application basically asks for some details of user like Name, Age, Address and p

5条回答
  •  执念已碎
    2020-12-03 06:01

    I suggest you to separate the code into three parts:

    • Read input (like name in your example)
    • Do what you need to do with that input
    • Print the results

    You do not need to test reading input and printing results, as that's Java code that is already tested by people writing Java.

    The only thing you need to test is the thing you are doing, whatever that is. Unit tests are named like that because they tests units of code in isolation. You don't test the whole program, you test small pieces that are self-contained and have a well-defined function.

    In unit tests, you should not rely on input/output operations. You should provide inputs and expected outputs directly in the unit test. It is sometimes convenient to use File reading operations to supply input or output (e.g. if the amount of data is huge), but as a general rule the more you go into input/output in your unit tests, the more complex they become and you are more likely not to do unit, but integration tests.

    In your case, you use name somehow. If that is the only parameter, then make a method - let's call it nameConsumer - that takes that name, does something and returns its result. In your unit tests, do something like this:

    @Test
    public void testNameConsumer() {
        // Prepare inputs
        String name = "Jon";
        String result = nameConsumer(name);
        assertEquals("Doe", result);
    }
    

    Move your println and readLine calls to other methods and use around nameConsumer, but not in your unit tests.

    Read more about this here:

    • http://haacked.com/archive/2008/07/22/unit-test-boundaries.aspx
    • C# example, but still: http://dotnet.dzone.com/news/unit-testing-file-io

    Keep it simple, it pays off.

提交回复
热议问题