2014-09-30 112 views
1

我写使用的TestCase我的Django应用程序的测试,并希望能够将参数传递给父类的设置方法如下所示:传递额外参数的TestCase设置

from django.test import TestCase 

class ParentTestCase(TestCase): 
    def setUp(self, my_param): 
     super(ParentTestCase, self).setUp() 
     self.my_param = my_param 

    def test_something(self): 
     print('hello world!') 

class ChildTestCase(ParentTestCase): 
    def setUp(self): 
     super(ChildTestCase, self).setUp(my_param='foobar') 

    def test_something(self): 
     super(ChildTestCase, self).test_something() 

但是,我得到的以下错误:

TypeError: setUp() takes exactly 2 arguments (1 given) 

我知道,这是因为只有自己仍然是过去了,我需要改写为__init__类来得到这个工作。我是Python的新手,不确定如何实现这一点。任何帮助表示赞赏!

+0

就我个人而言,我被教导说,使用两个不同方法的同名名称通常是不好的做法。这是我对这件事的第一次猜测。你尝试过改变名称,说:'P_set_up'和'C_set_up'? – 2014-09-30 02:35:36

+0

我应该更清楚。我想继续从TestCase的setUp方法继承并扩展它。 – 2014-09-30 02:39:42

回答

1

测试运行器将仅以self作为参数调用您的ParentTestCase.setup。因此,您将添加一个默认值这种情况下例如为:

class ParentTestCase(TestCase): 
    def setUp(self, my_param=None): 
     if my_param is None: 
      # Do something different 
     else: 
      self.my_param = my_param 

注意:要小心,不要使用可变值作为默认值(见"Least Astonishment" and the Mutable Default Argument有详细介绍)。

相关问题