代码之家  ›  专栏  ›  技术社区  ›  Purrell

是否在测试用例之外使用TestCase.assertEqual()呢?

  •  3
  • Purrell  · 技术社区  · 17 年前

    我有一个实用程序类,它存储对某些单元测试用例有用的方法。我希望这些助手方法能够执行断言/失败等操作,但似乎我不能使用这些方法,因为它们期望TestCase作为第一个参数。。。

    我希望能够在testcase代码之外存储公共方法,并继续在其中使用断言,这有可能吗?它们最终用于测试用例代码中。

    unittest_foo.py:

    import unittest
    from common_methods import *
    class TestPayments(unittest.TestCase):
     def test_0(self):
      common_method1("foo")
    

    from unittest import TestCase
    def common_method1():
        blah=stuff
        TestCase.failUnless(len(blah) > 5)
            ...
    ...
    

    TypeError: unbound method failUnless() must be called with TestCase instance as first argument (got bool instance instead)

    2 回复  |  直到 10 年前
        1
  •  4
  •   Ned Batchelder    17 年前

    这通常通过多重继承来实现:

    通用_methods.py:

    class CommonMethods:
      def common_method1(self, stuff):
        blah=stuff
        self.failUnless(len(blah) > 5)
            ...
    ...
    

    import unittest
    from common_methods import CommonMethods
    class TestPayments(unittest.TestCase, CommonMethods):
     def test_0(self):
      self.common_method1("foo")
    
        2
  •  1
  •   Parag Tyagi    10 年前

    听起来你想要这个,至少从错误。。。

    unittest_foo.py:

    import unittest
    from common_methods import *
    
    class TestPayments(unittest.TestCase):
        def test_0(self):
            common_method1(self, "foo")
    

    通用_methods.py:

    def common_method1( self, stuff ):
        blah=stuff
        self.failUnless(len(blah) > 5)