测试异常错误
Error in test exception
这是我要测试的假人 class:
class Meter:
def __init__(self, meterInfo):
self.b1pos = meterInfo['b1pos']
def setMeter(self):
print 'Initializing'
try:
print 'Connecting'
except IOError as message:
print message
def readSignal(self, ele_name):
try:
if ele_name in ("b1", "b2"):
readValue = 0.0
readValue1 = 0.0
return readValue, readValue1
else:
readValue = 0.0
readValue1 = 0.0
return readValue, readValue1
except IOError as message:
print message
这是我的单元测试:
class TestMeter(unittest.TestCase):
def testSetMeter(self):
m = meter.Meter({'b1pos': 'b1pos'})
self.assertRaises(IOError, m.setMeter())
def testReadSignal(self):
m = meter.Meter({'b1pos': 'b1pos'})
a, b = m.readSignal('b1')
self.assertTrue(isinstance(a, numbers.Number))
self.assertTrue(isinstance(b, numbers.Number))
self.assertRaises(IOError, m.readSignal('b1'))
if __name__ == '__main__':
unittest.main()
对于 testSetMeter() 我没有任何问题,但是对于 testReadSignal() 它给了我:"TypeError: 'tuple' object is not callable"
我知道这个错误与 radSignal 的 return 有关,但我该如何解决呢?
我试过:
def testReadSignal(self):
m = meter.Meter({'b1pos': 'b1pos'})
a, b = m.readSignal('b1')
self.assertTrue(isinstance(a, numbers.Number))
self.assertTrue(isinstance(b, numbers.Number))
with self.assertRaises(IOError):
m.readSignal('b1')
但这是输出:
AssertionError: IOError not raised
必须改用pytest.raises。见 docs.
with self.raises(IOError):
m.readSignal('b1')
似乎测试也会失败,因为这些方法正在捕获异常,而不是引发异常。
和
self.assertRaises(Exception, m.readSignal('b1'))
我解决了问题
这是我要测试的假人 class:
class Meter:
def __init__(self, meterInfo):
self.b1pos = meterInfo['b1pos']
def setMeter(self):
print 'Initializing'
try:
print 'Connecting'
except IOError as message:
print message
def readSignal(self, ele_name):
try:
if ele_name in ("b1", "b2"):
readValue = 0.0
readValue1 = 0.0
return readValue, readValue1
else:
readValue = 0.0
readValue1 = 0.0
return readValue, readValue1
except IOError as message:
print message
这是我的单元测试:
class TestMeter(unittest.TestCase):
def testSetMeter(self):
m = meter.Meter({'b1pos': 'b1pos'})
self.assertRaises(IOError, m.setMeter())
def testReadSignal(self):
m = meter.Meter({'b1pos': 'b1pos'})
a, b = m.readSignal('b1')
self.assertTrue(isinstance(a, numbers.Number))
self.assertTrue(isinstance(b, numbers.Number))
self.assertRaises(IOError, m.readSignal('b1'))
if __name__ == '__main__':
unittest.main()
对于 testSetMeter() 我没有任何问题,但是对于 testReadSignal() 它给了我:"TypeError: 'tuple' object is not callable" 我知道这个错误与 radSignal 的 return 有关,但我该如何解决呢? 我试过:
def testReadSignal(self):
m = meter.Meter({'b1pos': 'b1pos'})
a, b = m.readSignal('b1')
self.assertTrue(isinstance(a, numbers.Number))
self.assertTrue(isinstance(b, numbers.Number))
with self.assertRaises(IOError):
m.readSignal('b1')
但这是输出:
AssertionError: IOError not raised
必须改用pytest.raises。见 docs.
with self.raises(IOError):
m.readSignal('b1')
似乎测试也会失败,因为这些方法正在捕获异常,而不是引发异常。
和
self.assertRaises(Exception, m.readSignal('b1'))
我解决了问题