calculator.py
class Count:
def __init__(self,a,b):
self.a=int(a)
self.b=int(b)
def add(self):
return self.a+self.b
def sub(self):
return self.a-self.b
test.py
from calculator import Count
import unittest
class TestAdd(unittest.TestCase):
def setUp(self):
print("test add start")
def test_add(self):
j=Count(2,3)
self.assertEqual(j.add(),5)
def test_add2(self):
j=Count(41,76)
self.assertEqual(j.add(),117)
def tearDown(self):
print("test add end")
class TestSub(unittest.TestCase):
def setUp(self):
print("test sub start")
def test_sub(self):
j=Count(2,3)
self.assertEqual(j.sub(),-1)
def test_sub2(self):
j=Count(71,46)
self.assertEqual(j.sub(),25)
def tearDown(self):
print("test sub end")
if __name__ == '__main__':
suite = unittest.TestSuite()
suite.addTest(TestAdd("test_add"))
suite.addTest(TestAdd("test_add2"))
suite.addTest(TestSub("test_sub"))
suite.addTest(TestSub("test_sub2"))
runner=unittest.TextTestRunner()
runner.run(suite)
或者可以把setUp()和tearDown()所做的事情封装成一个测试类
from calculator import Count
import unittest
class MyTest(unittest.TestCase):
def setUp(self):
print("test add start")
def tearDown(self):
print("test add end")
class TestAdd(MyTest):
def test_add(self):
j=Count(2,3)
self.assertEqual(j.add(),5)
def test_add2(self):
j=Count(41,76)
self.assertEqual(j.add(),117)
class TestSub(MyTest):
def test_sub(self):
j=Count(2,3)
self.assertEqual(j.sub(),-1)
def test_sub2(self):
j=Count(71,46)
self.assertEqual(j.sub(),25)
if __name__ == '__main__':
unittest.main()