Accepted answer

you can replace with you own stream by calling system.setin(inputstream in). inputstream can be a byte array:

inputstream sysinbackup =; // backup to restore it later
bytearrayinputstream in = new bytearrayinputstream("my string".getbytes());

// do your thing

// optionally, reset to its original

different approach can be make this method more testable by passing in and out as parameters:

public static int testuserinput(inputstream in,printstream out) {
    scanner keyboard = new scanner(in);
    out.println("give a number between 1 and 10");
    int input = keyboard.nextint();

    while (input < 1 || input > 10) {
        out.println("wrong number, try again.");
        input = keyboard.nextint();

    return input;


i've found it helpful to create an interface that defines methods similar to and then use that for reading or writing to the system.out. the real implementation will delegate to system.console() while your junit version can be a mock object with canned input and expected responses.

for example, you'd construct a mockconsole that contained the canned input from the user. the mock implementation would pop an input string off the list each time readline was called. it would also gather all of the output written to a list of responses. at the end of the test, if all went well, then all of your input would have been read and you can assert on the output.


you might start by extracting out the logic that retrieves the number from the keyboard into its own method. then you can test the validation logic without worrying about the keyboard. in order to test the keyboard.nextint() call you may want to consider using a mock object.


i have fixed the problem about read from stdin to simulate a console...

my problems was i'd like try write in junit test the console to create a certain object...

the problem is like all you say : how can i write in the stdin from junit test?

then at college i learn about redirections like you say system.setin(inputstream) change the stdin filedescriptor and you can write in then...

but there is one more proble to fix... the junit test block waiting read from your new inputstream, so you need create a thread to read from the inputstream and from junit test thread write in the new stdin... first you have to write in the stdin because if you write later of create the thread to read from stdin you likely will have race conditions... you can write in the inputstream before to read or you can read from inputstream before write...

this is my code, my english skill is bad i hope all you can understand the problem and the solution to simulate write in stdin from junit test.

private void readfromconsole(string data) throws interruptedexception {
    system.setin(new bytearrayinputstream(data.getbytes()));

    thread rc = new thread() {
        public void run() {
            study = new study();


i managed to find a simpler way. however, you have to use external library system.rules by @stefan birkner

i just took the example provided there, i think it couldn't have gotten more simpler:

import java.util.scanner;

public class summarize {
  public static int sumofnumbersfromsystemin() {
    scanner scanner = new scanner(;
    int firstsummand = scanner.nextint();
    int secondsummand = scanner.nextint();
    return firstsummand + secondsummand;


import static org.junit.assert.*;
import static*;

import org.junit.rule;
import org.junit.test;

public class summarizetest {
  public final textfromstandardinputstream systeminmock
    = emptystandardinputstream();

  public void summarizestwonumbers() {
    systeminmock.providelines("1", "2");
    assertequals(3, summarize.sumofnumbersfromsystemin());

the problem however in my case my second input has spaces and this makes the whole input stream null!


one common way to test similar code would be to extract a method that takes in a scanner and a printwriter, similar to this stackoverflow answer, and test that:

public void processuserinput() {
  processuserinput(new scanner(, system.out);

/** for testing. package-private if possible. */
public void processuserinput(scanner scanner, printwriter output) {
  output.println("give a number between 1 and 10");
  int input = scanner.nextint();

  while (input < 1 || input > 10) {
    output.println("wrong number, try again.");
    input = scanner.nextint();

  return input;

do note that you won't be able to read your output until the end, and you'll have to specify all of your input up front:

public void shouldprocessuserinput() {
  stringwriter output = new stringwriter();
  string input = "11\n"       // "wrong number, try again."
               + "10\n";

  assertequals(10, systemundertest.processuserinput(
      new scanner(input), new printwriter(output)));

  assertthat(output.tostring(), contains("wrong number, try again.")););

of course, rather than creating an overload method, you could also keep the "scanner" and "output" as mutable fields in your system under test. i tend to like keeping classes as stateless as possible, but that's not a very big concession if it matters to you or your coworkers/instructor.

you might also choose to put your test code in the same java package as the code under test (even if it's in a different source folder), which allows you to relax the visibility of the two parameter overload to be package-private.


to test drive your code, you should create a wrapper for system input/output functions. you can do this using dependency injection, giving us a class that can ask for new integers:

public static class integerasker {
    private final scanner scanner;
    private final printstream out;

    public integerasker(inputstream in, printstream out) {
        scanner = new scanner(in);
        this.out = out;

    public int ask(string message) {
        return scanner.nextint();

then you can create tests for your function, using a mock framework (i use mockito):

public void getsintegerwhenwithinboundsofonetoten() throws exception {
    integerasker asker = mock(integerasker.class);

    assertequals(getboundintegerfromuser(asker), 3);

public void asksfornewintegerwhenoutsideboundsofonetoten() throws exception {
    integerasker asker = mock(integerasker.class);
    when(asker.ask("give a number between 1 and 10")).thenreturn(99);
    when(asker.ask("wrong number, try again.")).thenreturn(3);


    verify(asker).ask("wrong number, try again.");

then write your function that passes the tests. the function is much cleaner since you can remove the asking/getting integer duplication and the actual system calls are encapsulated.

public static void main(string[] args) {
    getboundintegerfromuser(new integerasker(, system.out));

public static int getboundintegerfromuser(integerasker asker) {
    int input = asker.ask("give a number between 1 and 10");
    while (input < 1 || input > 10)
        input = asker.ask("wrong number, try again.");
    return input;

this may seem like overkill for your small example, but if you are building a larger application developing like this can payoff rather quickly.

Related Query

More Query from same tag