单元测试断言中的文字或表达式?
您更喜欢单元测试中断言中的文字值还是表达式? 这个小例子演示了我的意思 - 请注意注释:
[Test]
public function fromXML_works() : void {
var slideshow : Slideshow = SlideshowConverter.fromXML(xmlSample);
// do you prefer literal value "1":
assertEquals(slideshow.id, "1");
// ... or an expression like this:
assertEquals(slideshow.id, xmlSample.@id);
}
private var xmlSample : XML =
<slideshow id="1">
<someOtherTags />
</slideshow>;
表达式的好处是,当 XML 示例更改时,单元测试不会中断。 另一方面,我基本上直接在单元测试中直接提供了 SlideshowConverter 的一个方面的实现,但我不喜欢这一点(测试应该测试意图,而不是实现)。 我还可以想象使用表达式的测试更容易出现编程错误(例如,我可能在测试方法中的 E4X 表达式中犯了错误)。
您更喜欢哪种方法? 在现实世界的项目中,什么优势通常更重要?
Do you prefer literal values or expressions in your Asserts in your unit tests? This little example demonstrates what I mean - please pay attention to the comments:
[Test]
public function fromXML_works() : void {
var slideshow : Slideshow = SlideshowConverter.fromXML(xmlSample);
// do you prefer literal value "1":
assertEquals(slideshow.id, "1");
// ... or an expression like this:
assertEquals(slideshow.id, xmlSample.@id);
}
private var xmlSample : XML =
<slideshow id="1">
<someOtherTags />
</slideshow>;
The nice thing about the expression is that when the XML sample changes, the unit test will not break. On the other hand, I've basically provided an implementation of one aspect of my SlideshowConverter directly in my unit test which I don't like (the test should test intent, not implementation). I can also imagine that tests using expressions will be more prone to programming errors (I could have, for example, made a mistake in my E4X expression in my test method).
What approach do you prefer? What advantage is usually more important on real world projects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
特别是因为您已经标记了此 TDD:坚持使用文字。 在代码存在之前编写一个测试来通过它,你对自己说,“自我:如果我有这个函数并给它那些参数,那么这就是我会得到的。” 其中 this 是一个非常具体的值。 不要把它藏起来; 不要抽象它——只需将值放入测试中即可。 它还增强了测试的文档价值。
Particularly since you've tagged this TDD: stick with literals. Writing a test before code exists to pass it, you say to yourself, "Self: if I had this function and gave it those parameters, then this is what I would get back." Where this is a very specific value. Don't hide it away; don't abstract it - just put the value into the test. It enhances the documentation value of the test as well.
就我个人而言,我喜欢在测试中使用常量 - 它确保测试装置简单明了。 另外,正如您所提到的,它避免了测试本身的编程错误,这可能会隐藏真实代码中的编程错误。
Personally, I like to use constants within my tests - it ensures that the test fixtures are simple and straightforward. Plus, as you mention, it avoids programming errors in the test itself, which may hide programming errors in the real code.