简体   繁体   English

unittest,从其他文件运行测试

[英]unittest, running test from other file

I can't seem to get the Test1.test_something() in test2 to work.. not sure if it's because they are both inheriting from the same base? 我似乎无法让test2中的Test1.test_something()正常工作..不确定是否是因为它们都从同一个基础继承?

Helper.py: Helper.py:

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

Test1.py 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 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()

Now, I had this working previously, when I had the setUp for test1 and test2 within their classes, but once I had them both inherit from baseTest, I started getting a unbound method <method> must be called with Test instance as first argument (got nothing instead) . 现在,我以前有这个工作,当我在他们的类中拥有test1和test2的setUp时,但是一旦我让它们都从baseTest继承,我就开始得到一个unbound method <method> must be called with Test instance as first argument (got nothing instead) Any suggestions? 有什么建议么?

The problem is that Test1.test_something() is an instance method, not a class method. 问题在于Test1.test_something()是实例方法,而不是类方法。 So you can't just call it like that (besides, even if it is class method, it should have been Test1.test1.test_something ). 因此,您不能只是这样调用它(此外,即使它是类方法,它也应该是Test1.test1.test_something )。

One way to do it (without messing around with the unittest.TestCase mechanism): 一种方法(不弄乱unittest.TestCase机制):

Test2.py

import Test1

class test2(Test1.test1):
    # whatever else

And you're done, test2 inherits Test1.test1.test_something() automatically. Test1.test1.test_something()test2自动继承了Test1.test1.test_something() If you need your test2 's test_something to do extra stuff, just do super(test2, self).test_something() within your overridden definition of test_something in test2 class. 如果您需要用test2test_something做更多的事情,只需在test2类中对test_something的重写定义中进行super(test2, self).test_something() test_something

Move the tests that are shared by both Test1 and Test2 classes into BaseTest : 将同时由Test1Test2类共享的测试移动到BaseTest

test.py: 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: test2.py:

import test
import unittest
import sys

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM