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
I suggest you to separate the code into three parts:
name in your example)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:
Keep it simple, it pays off.