YAGNI在编写测试时也适用吗? [英] Does YAGNI also apply when writing tests?

查看:82
本文介绍了YAGNI在编写测试时也适用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写代码时,我只在需要时编写所需的功能.

这种方法也适用于编写测试吗?

我应该为每个用例事先写一个测试,只是为了安全起见,还是应该在遇到用例时才编写测试?

解决方案

我认为,编写方法时,您应该同时测试预期的和潜在的错误路径.这并不意味着您应该扩展设计以涵盖所有可能的用途-将其保留在需要时使用,但是您应该确保测试在面对无效参数或其他条件的情况下定义了预期的行为. 据我了解,

YAGNI意味着您不应该开发尚未使用的功能.从这个意义上讲,您不应该编写测试来驱动您开发不需要的代码.不过,我怀疑那不是您要问的.

在这种情况下,我将更关注是否应该编写涵盖意外用途的测试-例如,传递null或超出范围参数导致的错误-还是重复仅针对数据而异的测试,不是功能.如前所述,在前一种情况下,我会说是".您的测试将记录遇到错误时方法的预期行为.这对于使用您的方法的人来说是重要的信息.

在后一种情况下,我无法给出确切的答案.您当然希望测试保持DRY状态-不要编写仅重复另一个测试的测试,即使该测试具有不同的数据.另外,除非您练习数据的极端情况,否则您可能不会发现潜在的设计问题.一个简单的示例是一种计算两个整数之和的方法:如果将其同时作为两个参数传递给maxint,会发生什么情况?如果您只有一项测试,那么您可能会错过此行为.显然,这与上一点有关.只有您可以确定何时确实需要进行测试.

When I write code I only write the functions I need as I need them.

Does this approach also apply to writing tests?

Should I write a test in advance for every use-case I can think of just to play it safe or should I only write tests for a use-case as I come upon it?

解决方案

I think that when you write a method you should test both expected and potential error paths. This doesn't mean that you should expand your design to encompass every potential use -- leave that for when it's needed, but you should make sure that your tests have defined the expected behavior in the face of invalid parameters or other conditions.

YAGNI, as I understand it, means that you shouldn't develop features that are not yet needed. In that sense, you shouldn't write a test that drives you to develop code that's not needed. I suspect, though, that's not what you are asking about.

In this context I'd be more concerned with whether you should write tests that cover unexpected uses -- for example, errors due passing null or out of range parameters -- or repeating tests that only differ with respect to the data, not the functionality. In the former case, as I indicated above, I would say yes. Your tests will document the expected behavior of your method in the face of errors. This is important information to people who use your method.

In the latter case, I'm less able to give you a definitive answer. You certainly want your tests to remain DRY -- don't write a test that simply repeats another test even if it has different data. Alternatively, you may not discover potential design issues unless you exercise the edge cases of your data. A simple example is a method that computes a sum of two integers: what happens if you pass it maxint as both parameters? If you only have one test, then you may miss this behavior. Obviously, this is related to the previous point. Only you can be sure when a test is really needed or not.

这篇关于YAGNI在编写测试时也适用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆