编写描述性单元测试 [英] Write descriptive unit tests
问题描述
我正在尝试用Python编写单元测试,并且很难找到一种描述性的方法来做事。我有一个JavaScript背景,我使用 mocha
这有助于我描述。
I'm trying to write unit tests in Python and struggle to find a descriptive way to do things. I have a JavaScript background and I use mocha
which helps me be descriptive.
这就是我所说的描述性:
This is what I mean by "descriptive":
foo.js
exports.foo = function (type, isLogged, iOk) {
if (type === undefined) throw new Error('a cannot be undefined');
if (isLogged === undefined) throw new Error('b cannot be undefined');
if (isLogged) {
if (type === 'WRITER') {
return isOk ? "writer" : -1;
} else {
return "something else"
}
}
}
foo.spec.js
describe('#foo()', function () {
context('when type is undefined', function () {
...
})
context('when isLogged is undefined', function () {
...
})
context('when type is defined', function () {
context('when isLogger is not defined', function () {
...
})
context('when isLogged is defined', function () {
context('when type is not WRITER', function () {
...
})
context('when type is WRITER', function () {
context('when isOk is true', function () {
...
})
})
})
})
})
当我用Python编写单元测试时,我最终会得到这样的结果:
While when I write unit tests in Python, I end up with somthing like this:
foo.spec.py
class TestFoo:
def test_when_type_is_undefined(self):
...
def test_when_isLogged_is_undefined(self):
...
# This test name is too long
def test_when_type_is_defined_and_isLogged_is_undefined_and_type_is_writer_when_is_ok_is_true(self):
...
如何以更好的方式构建这些测试?有关描述性单元测试的最佳实践是什么?是否有好的单元测试的好例子?
How to structure these test in a better way? What are the best practices regarding descriptive unit testing? Are there good examples of good unit tests?
推荐答案
你可以使用 pyspecs 在你的代码中有更多类似BDD的语法。
You can use pyspecs to have a more BDD-like syntax in your code.
from pyspecs import given, when, then, and_, the, this
with given.two_operands:
a = 2
b = 3
with when.supplied_to_the_add_function:
total = a + b
with then.the_total_should_be_mathmatically_correct:
the(total).should.equal(5)
with and_.the_total_should_be_greater_than_either_operand:
the(total).should.be_greater_than(a)
the(total).should.be_greater_than(b)
with when.supplied_to_the_subtract_function:
difference = b - a
with then.the_difference_should_be_mathmatically_correct:
the(difference).should.equal(1)
输出
Output
# run_pyspecs.py
| • given two operands
| • when supplied to the add function
| • then the total should be mathmatically correct
| • and the total should be greater than either operand
| • when supplied to the subtract function
| • then the difference should be mathmatically correct
(ok) 6 passed (6 steps, 1 scenarios in 0.0002 seconds)
这篇关于编写描述性单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!