I have question about JUnit tests.
I am trying to test my code and for some unknown reason it keeps failing me all the time. This is code I try to test:
public void userInputWord() throws Exception{
System.out.println("****Please input your word, 2 to 8 ***");
System.out.println("**********character strings.**********");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
inputWord = br.readLine();
setInputWord(inputWord);
setWordLenght(inputWord.length());
System.out.println("***Please input amount of words you***");
System.out.println("*************want to find*************");
try{
stringLadder = br.readLine();
setLadder(Integer.parseInt(stringLadder));
}catch(NumberFormatException nfe){
System.out.println("Your input must be integer value.");
}
searchForMatch();
}
Basically this method is asking user to input two values (starting word and how many words he wants to see as a WordLadder) I am assigning those values to set methods. My JUnit for this class is following:
public void testUserInputWord() {
Generation gener = new Generation();
StringReader read = new StringReader("broom");
Scanner scan = new Scanner(read);
gener.setInputWord(scan.toString());
assertEquals("broom", gener.getInputWord());
}
I never wrote JUnit before and just did some research, could anyone explain what am I doing wrong?
Well, the first problem is that you’re never calling the code you’re trying to test. All you’re testing at the moment is the getters and setters (for
ladderandinputWord).Unfortunately, testing the
userInputWordmethod is tricky, because it relies onSystem.in. You need to have a way of “faking” the user input. One option would be to make the method take aScanneror perhaps aReader. You could then create all the appropriate user input via aStringReader, so that the method would read the data you’d pre-programmed. You’d then test the results. If other parts of this class need user input too, you may want to change it so that your constructor takes something (again, possibly aScanner, possibly aReader) to represent user input. Again, you’d provide the test data when constructing your test instance.Fundamentally, the idea of “something to provide user input” is a dependency for the code you’re trying to test – and a lot of the skill of unit testing is working out how to provide dependencies which are under the control of your test. There are lots of approaches to this which are appropriate in different situations – in this case, you can probably just use an existing implementation (
StringReader) as the underlying data source instead of the console.