用户输入的单元测试 - Java
我正在尝试为我创建的游戏编写单元测试。 该游戏是一个井字棋实现,它与用户交互并从命令行获取输入。 我不确定如何编写一个测试来获取并检查用户输入。 例如: 运行时:程序要求用户输入姓名及其符号(“x”或“0”) 然后继续接受位置输入。
我是否创建一个 @Before 方法并在此方法中写入输入语句?或者有更好的方法来做到这一点吗? 将所有内容写在我的 @Before 方法中将会使其变得非常大。
有什么建议吗?请帮忙。
谢谢
I am trying to write unit tests for a game i have created.
The game is a tic tac toe implementation which interacts with the user and takes input from the command line.
I am not sure how i can go about writing a test which will take and check user input.
For example:
When run: the program asks user for entering name and his symbol ('x' or '0')
and then keep accepting inputs of position.
Do i create a @Before method and write input statements inside this method? or is there a better way to do this?
Writing everything in my @Before method will make it extremely big.
Any suggestions?? Please help.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
理想情况下,您可以将输入类拆分为接口和实现,然后创建一个 MockInput 用于测试目的。
当某些测试需要假用户输入时,您只需为该场合制作一个模拟输入并继续进行即可。符号和名称可以是硬编码的,但这种方式为您提供了一定的灵活性。
鉴于哈菲兹的回答,我们中的一个人显然回答了错误的问题……而且我不太确定是他。嗯,无论如何,这都会有帮助。
Ideally, you'd split your input class into an interface and an implementation, and then create a MockInput for testing purposes.
When some test needed a fake user input, you just whip up a mock one for the occasion and keep going. The symbol and name could be hard-coded, but this way gives you some flexibility.
Given hhafez's answer, one of us is clearly answering the wrong question... and I'm not so sure it's him. Ah well, this'll be helpful either way.
你说你想写
您不应该有一个类同时执行这两项任务,即获取并检查用户输入,这样的内聚性很差。
相反,有两个类:验证器(或检查器或您想称呼它的任何名称)和输入处理器,该输入处理器接受用户输入并构建验证器可以理解的一些对象。
一旦您分离了关注点,为您的验证器编写 junit 测试用例应该非常简单。至于用户输入类,请查看这个问题关于如何对基于控制台的应用程序进行单元测试
You say you want to write
You shouldn't have one class that does both, take and check user input, that's poor cohesion.
Instead have two classes a Validator (or checker or what ever you want to call it) and an input processor that takes the user input and builds some object that the Validator understands.
Once you have separated the concerns, writing a junit test case for your Validator should be quite straightforward. As for the user input class have a look at this question about how to unit test console based app