异常处理及测试

mac2025-01-14  7

try:有可能出现的异常 except异常类型as实例,捕获特定异常。 finally:无论是否遇到异常均会执行。 raise:手动抛出异常。

测试的实例

def get_formatted_name(first,last): full_name = "{}{}".format(first,last) return full_name.title() print(get_formatted_name("tom","lee"))

结果是: Tomlee 调用上面的main.py

import unittest from main import get_formatted_name class NameTestCase(unittest.TestCase): def test_title_name(self): formated_name = get_formatted_name("tom","Lee") self.assertEqual(formated_name,"Tomlee") if __name__ == '__main__': unittest.main()

结果是: OK

class Calculator: def __init__(self,x,y): self.x = x self.y = y def add(self): return self.x + self.y def subtract(self): return self.x - self.y if __name__ == '__main__': c = Calculator(5,3) print(c.add())

结果是: 8 调用上面的calculator

import unittest from calculator import Calculator class CalculatorTest(unittest.TestCase): def test_add(self): c = Calculator(5,3) self.assertEqual(8,c.add()) if __name__ == '__main__': unittest.main()

结果是: ok

import unittest from calculator import Calculator class CalculatorTest(unittest.TestCase): def test_add(self): c = Calculator(5,3) self.assertEqual(8,c.add()) def test_subtract(self): c = Calculator(8, 4) self.assertEqual(4,c.subtract()) if __name__ == '__main__': unittest.main()

结果是:ok

import unittest from calculator import Calculator class CalculatorTest(unittest.TestCase): def setUp(self): self.c = Calculator(5,3) def test_add(self): # c = Calculator(5,3) self.assertEqual(8,self.c.add()) def test_subtract(self): # c = Calculator(8, 4) self.assertEqual(2,self.c.subtract()) if __name__ == '__main__': unittest.main()

结果是: OK

import unittest from calculator import Calculator class CalculatorTest(unittest.TestCase): def setUp(self): self.c = Calculator(5,3) def test_add(self): # c = Calculator(5,3) self.assertEqual(8,self.c.add()) def test_subtract(self): # c = Calculator(8, 4) self.assertEqual(2,self.c.subtract()) def tearDown(self): #释放C文件 del self.c if __name__ == '__main__': unittest.main()

最新回复(0)