繁体   English   中英

如何在从unittest.TestCase继承的类中创建通用方法?

[英]How do you create a common method within a class that inherited from unittest.TestCase?

假设我有以下代码:

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

file2.py ,我想从file1.py调用call common_verify_method() 一种方法我可以调用从inhereting做到这一点TestATestB 以下工作正常:

Class TestMyOtherCode(TestA)
    def my_other_code(self):
        results = do_something()
        self.common_verify_method(results)

如果我不想从TestA ,我该如何调用common_verify_method() 如果使用合成,则会出现以下错误:

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

而不是从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):
...

我尝试了您的代码以在两个类(即TestA和TestMyOtherCode)中获得预期的结果。 我创建了两个python文件,分别称为Sample1和Sample2。

这是一个代码

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

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)

我在python中使用了Composition方法。 它工作正常,并给出了预期的结果。

试试吧...

暂无
暂无

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

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