I am trying to understand how can I test a user's input (please note I am not trying to do a mock test but a test of actual user's input)
Currently as you may see in my program I have hard coded the values for my test case and it is passing all tests but how can I get a user's input and test it .
Is there a way where I can call System.in my constructor and pass it when I create an instance of MyClass1 in the test class?
Please, if possible give me some example code so I can better understand.
If I have a interface as such
public interface IMyClass{
public int getvalue1();
public int getvalue2();
public int getvalue3();
}
and then interface implementation as such
public class MyClass1 implements MyClass{
private int _value1 = 0;
private int _value2 = 0;
private int _value3 = 0;
public MyClass1(int number1, int number2, int number3)
{
_value1 = number1;
_value2 = number2;
_value3 = number3;
}
public void setLength1(int value1)
{
_value1 = value1;
}
public void setLength2(int length2)
{
_value2 = value2;
}
public void setLength3(int length3)
{
_value3 = value3;
}
public int getValue1()
{
return _value1;
}
public int getValue2()
{
return _value2;
}
public int getValue3()
{
return _value3;
}
}
and finally a test class as such:
public class ClasTest extends TestCase {
public void testNumbers()
{
MyClass1 numbers= new MyClass1(1,2,3);
assertThat(numbers.getValue1(),is(not(numbers.getValue2())));
}
}
Thankyou, I appreciate any help.
Use System.setIn(new InputSteam());
and then write to the input stream passed in to System.in
see: JUnit: How to simulate System.in testing?
Single Input
String data = "Users Input";
System.setIn(new ByteArrayInputStream(data.getBytes()));
Scanner scanner = new Scanner(System.in);
System.out.println(scanner.nextLine());
Result
Users Input
Multiple Inputs
String data = "Users Input" +
"\nA second line of user input.";
System.setIn(new ByteArrayInputStream(data.getBytes()));
Scanner scanner = new Scanner(System.in);
System.out.println("Line 1: " + scanner.nextLine());
System.out.println("Line 2: " + scanner.nextLine());
Result
Line 1: Users Input
Line 2: A second line of user input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With