I'm very new to JUnit and Unit Testing and have a question regarding mocking user input to the Scanner object. I have the following code that I would like to test. Very Basic.
Run Code
import java.util.Scanner;
public class MyGame{
public MyGame() {
Scanner response = new Scanner(System.in);
int game;
System.out.println("Enter a game.");
System.out.println("Press 1 for Super Awesome Bros.");
System.out.println("Press 2 for a Random game.");
game = response.nextInt();
if (game == 1){
System.out.println("Super Awesome Bros.");
}
}
}
Here is my Testcase
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.contrib.java.lang.system.StandardOutputStreamLog;
import org.junit.contrib.java.lang.system.TextFromStandardInputStream;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.contrib.java.lang.system.TextFromStandardInputStream.*;
@RunWith(JUnit4.class)
public class Testsuite {
@Rule
public final StandardOutputStreamLog out = new StandardOutputStreamLog();
@Rule
public final TextFromStandardInputStream in = emptyStandardInputStream();
@Test
public void printOutput() {
in.provideText("1\n");
new MyGame();
assertThat(out.getLog(), containsString("Super Awesome Bros."));
}
}
So in my Testcase, I'm trying to mock the input to be 1 so I can receive the expected output. But for some reason my code passes regardless of what the output is. I'm not sure what I'm doing wrong. The test should fail if the output is not what's expected. Can someone spot the issue? Again, I'm just trying to get a grasp of JUnit and Unit Testing. I'm use to testing in Python mostly. Thanks to everyone in advanced.