JUnit 命令行测试
之前已经问过这个问题,但没有澄清到我明白的程度。与我在这个主题上看到的一两个其他线程类似,我正在开发一个带有命令行输入的聊天客户端,用于登录/关闭、断开连接等,并且我不确定如何在 JUnit 测试中模拟它案件。其他回复表明我应该尝试将 System.in 更改为单独的 InputStream 但是...然后呢?
tl;dr:我的实际代码中有一个方法用于解析命令行输入,并且需要一种 JUnit 方法来测试这些输入是否已输入并得到适当处理。
This has been asked before, but was not clarified to the point where I get it. Similar to the one or two other threads I've seen on this subject, I'm working on a chat client with command line inputs for logging in/off, disconnecting, etc. and I am unsure how to simulate this in a JUnit test case. Other responses indicated that I should try changing the System.in to a separate InputStream but...then what?
tl;dr: I have a method in my actual code for parsing command line input, and need a JUnit way of testing that these were entered and appropriately processed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:看来我误解了这个问题。我通常使用术语“命令行输入”来指代给进程启动的命令行参数,而不是交互式控制台输入。然而......
将您的真实代码交给不同的
InputStream
,甚至可能是Reader
或Scanner
确实会有所帮助 - 任何可以分离“获取来自控制台的输入”部分。然后,您可以非常轻松地一次性伪造所有输入,使用 String 作为测试代码中的输入,然后将其转换为字节并将这些字节包装在 ByteArrayInputStream 中,或者直接将字符串包装在StringReader
。这样做的缺点是,没有简单的方法可以在一个命令之后“暂停”以检查结果。
您可能需要稍微改变设计,以便将读取输入的部分与处理输入的部分分开。读取部分可能是一个非常简单的循环,顺序为:
然后,您可以不通过单元测试测试该部分,或者编写一些相对原始的测试 - 但您可以广泛测试
handleInput
,如下所示它现在与输入源分离。原始答案
如果您已从真正启动应用程序的代码中提取了解析代码,那么很简单:运行该代码并检查结果。当然,如果您有某种封装选项的类,这将是最简单的。例如,您的
main
方法可能如下所示:然后您可以非常轻松地测试
Options.parse
。EDIT: It seems I misunderstood the question. I usually use the term "command line input" to refer to command line arguments given to the process to start with, rather than interactive console input. However...
Handing your real code either a different
InputStream
or possibly even aReader
orScanner
would indeed help - anything to separate the "getting input" part from the console. You can then fake the input all in one go pretty easily, using a String as input in your test code, and then either converting it to bytes and wrapping those bytes in aByteArrayInputStream
or wrapping the string directly inStringReader
.The downside of this is that there's no easy way of making this "pause" after one command in order to check the results.
You may want to alter the design somewhat so that the part which reads the input is separated from the part which handles the input. The reading part could be a very simple loop, on the order of:
You could then potentially leave that part untested by unit tests, or write some relatively primitive tests - but you can then test
handleInput
extensively, as it's now separated from the input source.Original answer
If you've extracted the parsing code from the code which really starts the application, it's easy: run that code, and check the results. This will be easiest if you have some sort of class encapsulating the options, of course. For example, your
main
method might look like this:Then you can just test
Options.parse
very easily.