[英]How do you create a common method within a class that inherited from unittest.TestCase?
Let's say I have the following code: 假设我有以下代码:
file1.py
class TestA(unittest.TestCase)
def test_something(self):
results = something()
self.common_verify_method(results)
def common_verify_method(self, results)
expected = expected_method()
self.assertEqual(results, expected) # this uses self.assertEqual
file2.py
Class TestB(unittest.TestCase):
def my_other_code(self):
results = do_something()
# Here I would like to call common_verify_method() from file1.py
In file2.py
, I would like to call call common_verify_method()
from file1.py
. 在
file2.py
,我想从file1.py
调用call common_verify_method()
。 One way I can call do this by inhereting from TestA
in TestB
. 一种方法我可以调用从inhereting做到这一点
TestA
中TestB
。 The following works OK: 以下工作正常:
Class TestMyOtherCode(TestA)
def my_other_code(self):
results = do_something()
self.common_verify_method(results)
If I don't want to inherent from TestA
, how can I call common_verify_method()
. 如果我不想从
TestA
,我该如何调用common_verify_method()
。 If I use composition, I get the following error: 如果使用合成,则会出现以下错误:
Class TestMyOtherCode(unittest.TestCase)
def my_other_code(self):
results = do_something()
test_a = TestA()
test_a.common_verify_method(results)
ValueError: no such test method in <class 'tests.file1.TestA'>: runTest
Instead of TestB
inheriting from TestA
, or the other way round, they should both inherit from a common base class: 而不是从
TestA
继承TestB
,或者从相反的方向继承,它们都应该从一个公共基类继承:
class CommonBase(unittest.TestCase)
def common_verify_method(self, results)
expected = expected_method()
self.assertEqual(results, expected) # this uses self.assertEqual
class TestA(CommonBase):
...
I tried your code to get the expected result in both classes (ie) TestA & TestMyOtherCode. 我尝试了您的代码以在两个类(即TestA和TestMyOtherCode)中获得预期的结果。 I created two python files let's say Sample1 & Sample2.
我创建了两个python文件,分别称为Sample1和Sample2。
Here is a code 这是一个代码
Sample1.py Sample1.py
import unittest
class TestA(unittest.TestCase):
def test_something(self):
results = 5
self.common_verify_method(results)
def common_verify_method(self, results):
expected = 5
self.assertEqual(results, expected)
Sample2.py Sample2.py
from Sample1 import TestA
import unittest
class TestMyOtherCode(unittest.TestCase):
def __init__(self):
self.other = TestA
def my_other_code(self):
results = 5
self.other.common_verify_method(results)
I used Composition method in python. 我在python中使用了Composition方法。 It works fine and gave expected result.
它工作正常,并给出了预期的结果。
Try it... 试试吧...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.