任何将参数从测试传递到 Python 单元测试测试的 setUp() 方法的方法?

Rob*_*ark 6 python arguments python-unittest

有没有办法从给定的测试中将参数传递给 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
Run Code Online (Sandbox Code Playgroud)

Rob*_*ark 7

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
Run Code Online (Sandbox Code Playgroud)