繁体   English   中英

如何在单元测试中测试特定案例?

[英]How do I test specific cases in unittest?

我已经阅读了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”从命令行执行一个测试文件,并以某种方式预先确定一系列输入和预期输出?


听起来您有一个长程序,其中包含许多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)

说得通?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM