Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 不可调用的资产_Python_Unit Testing - Fatal编程技术网

Python 不可调用的资产

Python 不可调用的资产,python,unit-testing,Python,Unit Testing,说我有课 class myClass(object): pname = "" def __getName(self): return pname def __setName(self, newname): if not isalpha(newname): raise ValueError("Error") elif self.pname = newname name = property(fge

说我有课

class myClass(object):
   pname = ""

   def __getName(self):
      return pname

   def __setName(self, newname):
      if not isalpha(newname):
         raise ValueError("Error")
      elif
         self.pname = newname

   name = property(fget=__getName,fset=__setName)

鉴于这些方法是私有的,并且我通过name访问pname,当AssertRaises只接受可调用的方法进行测试时,如何使用AssertRaises进行测试?

让您自己的方法可调用

class TestMyClass(unittest.TestCase):
    def test_should_raise(self):
        x = myClass()
        def assign_bad_name():
            x.name = "7"
        self.assertRaises(ValueError, assign_bad_name)

定义你自己的功能

class TestRaises(unittest.TestCase):
    def test_setter(self):
        def run_test():
            c = myClass()
            c.name = 12

        self.assertRaises(ValueError, run_test)

首先。请不要把时间浪费在具有
\u名称的“私有”方法上

第二。这样做

class TestMyClass( unittest.TestCase ):
    def setUp( self ):
        self.myclass= MyClass()
    def test_setName_should_fail( self ):
        try:
            self.myclass.name = 232
            self.fail( "Should have raised an exception" )
        except ValueError, e:
            self.assertEquals( "Error", e.msg )
在Python3(和2.7)中,您可以将
构造一起使用:

class TestMyClass(unittest.TestCase):
    def test_should_raise(self):
        x = myClass()
        with self.assertRaises(ValueError):
            x.name = "7"
这是代码开始变得漂亮