【问题标题】:Any way to pass args from test to setUp() method for a Python unittest test?有什么方法可以将 args 从测试传递到 Python unittest 测试的 setUp() 方法?
【发布时间】:2014-05-08 18:39:51
【问题描述】:

有没有办法从给定的测试中将参数传递给 setUp() 方法,或者其他方式来模拟这种情况?例如,

import unittest

class MyTests(unittest.TestCase):
    def setUp(self, my_arg):
        # use the value of my_arg in some way

    def test_1(self):
        # somehow have setUp use my_arg='foo'
        # do the test

    def test_2(self):
        # somehow have setUp use my_arg='bar'
        # do the test

【问题讨论】:

  • @Jan_Vlcinsky,请注意,我的问题是关于从测试中传递参数,而您提到的问题是关于从命令行传递参数。
  • 哦,我明白了。由于 SetUp 总是在任何 test_* 之前调用,我想,你想用不同的上下文运行测试集。您的答案是满足您需求的明确解决方案。

标签: python arguments python-unittest


【解决方案1】:

setUp() 是一种方便的方法,不必使用。除了(或除此之外)使用 setUp() 方法,您还可以使用自己的 setup 方法并直接从每个测试中调用它,例如,

class MyTests(unittest.TestCase):
    def _setup(self, my_arg):
        # do something with my_arg

    def test_1(self):
        self._setup(my_arg='foo')
        # do the test

    def test_2(self):
        self._setup(my_arg='bar')
        # do the test

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 2014-01-07
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多