测试驱动开发:无效方法
我一直在学习 TDD(使用 JUnit),并且对如何测试 void 方法有疑问,在这种情况下,我不能直接在方法的返回值上使用像 assertTrue() 这样的东西。例如,假设我有一个简单的基于控制台的应用程序,其中一部分在屏幕上打印菜单,假设使用此方法:
public void printMenu()
{
System.out.println("Menu:");
System.out.println("1. Option ONE");
System.out.println("2. Option TWO");
System.out.println("3. Exit");
}
我的问题是,我实际上必须测试此方法吗?如果是这样,我该怎么做?
I have been learning about TDD (using JUnit) and I have a doubt about how to go about testing void methods, in which case I can't directly use something like an assertTrue() on the return value of a method.. For example, say I have a simple console based application, and a part of it prints a menu on screen, say using this method:
public void printMenu()
{
System.out.println("Menu:");
System.out.println("1. Option ONE");
System.out.println("2. Option TWO");
System.out.println("3. Exit");
}
My question is, do I actually have to test this method?? And if so, how should I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对依赖静态方法调用的方法进行单元测试很困难。这不是返回某些东西或
void
的问题。您可以做的是将打印抽象为一个接口,并让您的类依赖于该接口(例如使用构造函数注入):在单元测试中,您可以模拟该接口并验证是否已在其上调用了正确的方法。这样您就可以独立测试 printMenu 。
It is difficult to unit test a method which relies on static method calls. It is not a matter of returning something or
void
. What you could do is abstract the printing into an interface and have your class depend on this interface (using constructor injection for example):In your unit test you could mock the interface and verify if correct methods have been called on it. This way you could test the printMenu in independently.
第一:测试 UI 很困难。有些人不愿意测试这样的东西,因为编写有意义的测试而不是脆弱到无用的程度是非常困难的。我不会费心去测试这个方法。
但是:
如果您想测试菜单生成,因为您的菜单代码很复杂并且您需要确保其正常工作的方法,那么您有多种选择。
First: testing UI is hard. Some people don't bother testing things like this because it is very difficult to write meaningful tests that aren't fragile to the point of uselessness. I wouldn't bother testing this method.
But:
If you want to test menu generation, because your menu code is complex and you need ways to ensure that it works, you have a couple choices.
捕获控制台输出并与预期进行比较
capture the console output and compare to expectations
您无法对该方法进行单元测试。
此方法不执行单元测试所需的逻辑或处理。
如果需要对打印菜单进行单元测试,可以考虑将结果输出到文本文件。
然后读取文本文件并比较菜单文本。
You can not unit test this method.
This method does no logic or processing that you need to unit test.
If you need to unit test the Print Menu, you can consider outputing the result to a text file.
Then read the text file and compare the menu texts..