unittest,从其他文件运行测试

时间:2013-07-25 19:51:27

标签: python unit-testing

我似乎无法让test2中的Test1.test_something()工作..不确定是不是因为它们都是从同一个基础继承而来?

Helper.py:

class baseTest(unittest.TestCase):
    def setUp(self, param="Something"):
        print param
        pass 

Test1.py

from Helper import baseTest

class test1(baseTest):

    def setUp(self):
        super(test1, self).setUp('foo')        

    def test_something(self):
        assert 1 == 1, "One does not equal one."

Test2.py

from Helper import baseTest
import Test1

class test2(baseTest):

    def setUp(self):
        super(test2, self).setUp('bar')

    def test_something(self):
        Test1.test_somehing()

现在,我之前有这个工作,当我在他们的类中有testUp和test2时,但是一旦我让他们都从baseTest继承,我开始得到unbound method <method> must be called with Test instance as first argument (got nothing instead)。有什么建议吗?

2 个答案:

答案 0 :(得分:0)

问题是Test1.test_something()是实例方法,而不是类方法。所以你不能像那样调用它(此外,即使它是类方法,也应该是Test1.test1.test_something)。

一种方法(不用弄乱unittest.TestCase机制):

Test2.py

import Test1

class test2(Test1.test1):
    # whatever else

您已完成,test2会自动继承Test1.test1.test_something()。如果您需要test2 test_something来做额外的事情,只需在super(test2, self).test_something()课程中test_something的被覆盖定义中test2

答案 1 :(得分:0)

Test1Test2类共享的测试移至BaseTest

test.py:

import unittest
import sys

class BaseTest(unittest.TestCase):
    def setUp(self, param="Something"):
        print param
        pass
    def test_something(self):
        assert 1 == 1, "One does not equal one."    

class Test1(BaseTest):
    def setUp(self):
        super(Test1, self).setUp('foo')        

test2.py:

import test
import unittest
import sys

class Test2(test.BaseTest):
    def setUp(self):
        super(Test2, self).setUp('bar')