如何将参数从测试传递给Python unittest的setUp()方法?

10 投票
1 回答
4665 浏览
提问于 2025-04-18 05:53

有没有办法从某个测试中给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

1 个回答

12

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

撰写回答