Hi Everyone, i need make a test unit for a input keyboard in Java, Exists any way easy to do it?
Thanks.
Hi Everyone, i need make a test unit for a input keyboard in Java, Exists any way easy to do it?
Thanks.
Factor out the code that reads the keyboard, make it an interface. Then create two implementations, one for production which does the "real" Java code to read the keyboard; the second can be accessed from code, in particular from your JUnit test.
Using the latter, your test can "type" whatever input is needed.
Added:
This is not valid code, I'm typing it off the top of my head! This is also just one way to do it: gpampara's approach below to make your own Streams would also work. It depends on your testing needs.
First make an interface
public interface Keyboard
{
public int getInt() ;
}
Then the "real" implemention:
public class RealKeyboard
implements Keyboard
{
// I haven't done Java keyboard reading in ages, so this is
// likely not how to do it, but you should get the idea
private BufferedReader __r ;
public RealKeyboard( BufferedReader r )
{
__r = r ;
}
public int getInt()
{
// whatever you need to do with __r
}
}
Then here's one possible test implementation:
public class TestKeyboard
implements Keyboard
{
private int __value ;
public TestKeyboard( int value )
{
__value = value ;
}
public int getInt()
{
return __value ;
}
}
This of course will always return the same value, which probably isn't what you want. You could do an implementation with a setInt() method, so that your test class could set the value during the test, or you could pass in a list of values to the constructor, and return each in sequence. Depends on what you need to test.
Then your calling code is simply passed one of these:
public class SomeConsumer
{
private Keyboard __k ;
public SomeConsumer( Keyboard k )
{
__k = k ;
}
// use it in your methods...
}
You could use Spring to inject it, or just hard-code it in your "production" code. But in your tests you can pass in one of your test implementations.
Write your classes to separate the actual keyboard input from the processing of the keyboard input, then test the two separately.
As for the keyboard input itself, put NO functionality in there beyond reading keys--this way it will either work or it won't... You can also mock out the classes feeding you the keys and have your mocked classes feed "known" keys to your classes under test.
Similar to the other answers, but I'd think that your abstraction should be based on a Stream
.
Seeing as the input from the keyboard is a stream as well, you could mock it out rather easily by providing a ByteArray[Input|Output]Stream (or something similarly appropriate) within the unit test.