如何在Java中测试(junit)输入键盘
我需要用Java为输入键盘制作一个测试单元,有什么方法可以轻松做到吗?
谢谢。
i need make a test unit for a input keyboard in Java, Exists any way easy to do it?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
分解出读取键盘的代码,使其成为一个接口。然后创建两个实现,一个用于生产,它执行“真正的”Java 代码来读取键盘;另一个用于生产。第二个可以从代码中访问,特别是从 JUnit 测试中。
使用后者,您的测试可以“键入”所需的任何输入。
已添加:
这不是有效的代码,我是凭空打出来的!这也只是实现此目的的一种方法:下面的 gpampara 方法可以让您的自己的 Streams 也可以工作。这取决于您的测试需求。
首先创建一个接口,
然后是“真正的”实现:
然后这是一个可能的测试实现:
这当然将始终返回相同的值,这可能不是您想要的。您可以使用 setInt() 方法进行实现,以便您的测试类可以在测试期间设置值,或者您可以将值列表传递给构造函数,然后按顺序返回每个值。取决于你需要测试什么。
然后,您的调用代码只需传递其中之一:
您可以使用 Spring 来注入它,或者只是将其硬编码到您的“生产”代码中。但在您的测试中,您可以传递您的测试实现之一。
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
Then the "real" implemention:
Then here's one possible test implementation:
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:
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.
与其他答案类似,但我认为您的抽象应该基于
Stream
。由于键盘的输入也是一个流,因此您可以通过在单元测试中提供 ByteArray[Input|Output]Stream (或类似的适当内容)来相当轻松地模拟它。
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.