Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unit test user input in java

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.

like image 799
user1462617 Avatar asked Apr 17 '13 17:04

user1462617


Video Answer


1 Answers

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.
like image 193
Mike Rylander Avatar answered Sep 19 '22 11:09

Mike Rylander