0

I created strategy for taking input because I want to test it.

This is my production code for taking input:

    //strategy interface
public interface BarcodeScannerInput {
public String getBarcode();
public int getBarcodeType();
}

//taking input from user (barcode and type)
class TakeInput implements BarcodeScannerInput {
private String barcode;
private int barcodeType;

public String getBarcode(){
    System.out.println("Enter barcode: ");
    Scanner code = new Scanner(System.in);
    barcode=code.nextLine();
    return barcode;
}
public int getBarcodeType(){
    System.out.println("Enter type of barcode (1-2):");
    Scanner type = new Scanner(System.in);
    barcodeType = type.nextInt();
    return barcodeType;
}
}

And my question is: How should look class for testing this input in junit tests?

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
Beast
  • 25
  • 1
  • 1
  • 11
  • 1
    This is not strategy pattern, are there relevant parts of the code missing? – John Jul 04 '15 at 09:23
  • You're showing the candidate to be mock, a irrelevant part (@user3360241), There isn't logic in this algorithm, You can use Powermock with mockito, for System.in, but.. Why do you want test this? – David Pérez Cabrera Jul 04 '15 at 09:41
  • 1
    I would say that the question should be: *How can i test class which depends on the system.in()* You can find similar question here:http://stackoverflow.com/questions/6415728/junit-testing-with-simulated-user-input. – John Jul 04 '15 at 09:44
  • 1
    @DavidPérezCabrera title is misleading. The question as is was already asked before. I wanted to see if there are some details which do not make this exact duplicate. – John Jul 04 '15 at 09:48
  • Yes, you have right, my title is misleading.. I have done a class which taking input with Scanner, and I want to create second class without Scanner, which could be simple tested. – Beast Jul 04 '15 at 18:51

1 Answers1

0

You can write a test by using the TextFromStandardInputStream rule of the System Rules library.

public class TakeInputTest() {
  @Rule
  public TextFromStandardInputStream systemInMock = emptyStandardInputStream();

  @Test
  public void readsBarCode() {
    TakeInput takeInput = new TakeInput();
    systemInMock.provideText("dummy barcode");
    assertEquals("dummy barcode", takeInput.getBarcode());
  }
}
Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72
  • It's for sure good solution, but I have to create a class which implements this BarcodeScannerInput interface. And this class should be simple to test it (without Scanner, only arguments or something like that, I tried few times and I can't do that alone.. ). – Beast Jul 04 '15 at 19:01