Why do Unit Test systems include useless assertive methods? [closed]

你。 提交于 2019-12-07 11:19:48

问题


I'm wondering why unittest systems like PHPUnit include what seems to be repetitive operators that just add overhead to the unit tests. I can understand a couple of those methods, but most seem like a total waste of time.

public function testPop(array stack)
{
    this->assertEquals('foo', array_pop(stack));
    this->assertEmpty(stack);
}

vs raw code (which is shorter and faster)

public function testPop(array stack)
{
    this->assert('foo' == array_pop(stack));
    this->assert(empty(stack));
}

Are these methods here for just so people that don't understand the language they are programming in can still write unit-tests? I'm sure the authors of this projects are smarter than myself so there must be a reason.


回答1:


These functions usually give more useful output. For example, an assertEquals test could tell you the expected and actual values, and that they were not equal.

For example, the following code:

this->assertEquals(1, 0);

Will produce this output:

Failed asserting that 0 matches expected 1.



回答2:


It's also about verbosity. This:

this->assert(foo == array_pop(stack));

Is much less verbose than:

this->assertEqual(foo, array_pop(stack));

Or even better:

$popped_value = array_pop(stack);
this->assertEqual($popped_value, foo);

In other frameworks (such as .NET's NUnit), it gets even better:

Assert.AreEqual(stack.Pop(), foo);

vs

var poppedValue = stack.Pop();
Assert.That(poppedValue, Is.EqualTo(foo));

Reading the last example is almost as if somebody was explaining the code to you. That's invaluable when you deal with old/somebody's else code.




回答3:


The reason is afaik to be able to present cleaner messages for failing tests, compare for example;

Test failed: 'foo' == array_pop(stack) assertion failed

to

Test failed: foo should be 2, actual value 5.


来源:https://stackoverflow.com/questions/9303071/why-do-unit-test-systems-include-useless-assertive-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!