如何在unittest中测试特定案例?

时间:2015-08-31 22:44:42

标签: python unit-testing

我已经阅读了unittest的python文档,发现它有点令人困惑。我编写了一个测试文件,其中包含测试各种类和方法的方法,包括:

class test_class_Graph(unittest.TestCase):
    def __init__(self):
        test_graph = Graph()
    def test_method__init__(self):
        assertEquals(x, y)
    def test_method_node(self, name):
        node = test_graph.node(name)
        assertIsInstance(node, Node)
        assertEquals(node.name, name)
class test_class_Node(unittest.TestCase):
    etc

我用'if-else'语句创建了一些测试方法,对应于实际方法中的'if-else'语句。这些是一种测试用例 - 在某些条件下,该方法应该单向运行,在其他条件下,我们期望该方法产生不同的东西。

在某些情况下,我不想将可能的条件集划分为'if-else'语句,我只想测试一些'样本'以获得更复杂的方法。例如,如果输入是特定的'X',我希望输出是特定的'Y'。

我在哪里编写这样的特定测试用例?我应该从命令行运行我的测试,在那里输入输入吗?或者我应该简单地使用'run'从命令行执行测试文件,并以某种方式预先选择输入和预期输出?

1 个答案:

答案 0 :(得分:0)

听起来你有一个很长的程序,有很多input()个电话和东西。我要测试的是尝试将尽可能多的实际程序代码移动到函数中,这样主要的只是打印和输入,它将数据发送到函数。然后这些函数返回您打印的数据。然后,您可以使用输入测试这些功能。所以这将是您的用户交互代码:

def main():
    x = input('what is your x?')
    y = input('what is your y?')
    z = input('And what is your z?')
    print(process_data(x, y, z))

然后你可以像这样测试你的逻辑: 啊,我知道,那是在使用unittest。

from mycode import process_data

class TestDataProcessing(unittest.TestCase):
    def try_one_thing(self):
        result = process_data(11, 44, 'Steve')
        assertEquals(result, 99)

    def try_another_thing(self):
        result = process_data(2, 6, 'Alan')
        assertEquals(result, 12)

有意义吗?