环境:windows,Eclipse,Python 3.3
import unittest
# 计算然后返回结果和过程的表达式
class Calculator(object):
def add(self, a, b):
return a+b, str(a)+'+'+str(b)+'='+str(a+b)
def minus(self, a, b):
return a-b, str(a)+'-'+str(b)+'='+str(a-b)
def multiply(self, a, b):
return a*b, str(a)+'*'+str(b)+'='+str(a*b)
def divide(self, a, b):
if b == 0:
return 9999, 'no'
return a/b, str(a)+'/'+str(b)+'='+str(a/b)
class CalculatorTestCase(unittest.TestCase):
def setUp(self):
self.cal = Calculator()
def tearDown(self):
self.cal = None
def test_add(self):
self.assertEqual(self.cal.add(1, 2), (3, '1+2=3'))
def test_minus(self):
self.assertEqual(self.cal.minus(10, 10), (0, '10-10=0'))
def test_multiply(self):
self.assertEqual(self.cal.multiply(1, 2), (2, '1*2=2'))
def test_divide(self):
self.assertEqual(self.cal.divide(1, 2), (0.5, '1/2=0.5'))
self.assertEqual(self.cal.divide(10, 10), (1.0, '10/10=1.0'))
self.assertEqual(self.cal.divide(0, 0), (9999, 'no'))
def suite():
suite = unittest.TestSuite()
suite.addTest(CalculatorTestCase("test_add"))
suite.addTest(CalculatorTestCase("test_minus"))
suite.addTest(CalculatorTestCase("test_multiply"))
suite.addTest(CalculatorTestCase("test_divide"))
return suite
if __name__ == "__main__":
unittest.main(defaultTest = 'suite')