11-1 城市和国家
代码:
import unittest def get_city_country(city, country): return city + ", " + country class place(unittest.TestCase): def test_get_city_country(self): str = get_city_country("Beijing", "China") self.assertEqual(str, "Beijing, China") unittest.main()
结果:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
11-2 人口数量
代码:
import unittest def get_city_country(city, country, population): return city + ", " + country + " - " + population class place(unittest.TestCase): def test_get_city_country(self): str = get_city_country("Beijing", "China") self.assertEqual(str, "Beijing, China") unittest.main()
结果:
Traceback (most recent call last):
File "C:/Users/lwj/PycharmProjects/test/test.py", line 20, in test_get_city_country
str = get_city_country("Beijing", "China")
TypeError: get_city_country() missing 1 required positional argument: 'population'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
代码:
import unittest def get_city_country(city, country, population = ""): if population: return city + ", " + country + " - " + population return city + ", " + country class place(unittest.TestCase): def test_get_city_country(self): str = get_city_country("Beijing", "China") self.assertEqual(str, "Beijing, China") unittest.main()
结果:
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
代码:
import unittest def get_city_country(city, country, population = ""): if population: return city + ", " + country + " - " + population return city + ", " + country class place(unittest.TestCase): def test_get_city_country(self): str = get_city_country("Beijing", "China") self.assertEqual(str, "Beijing, China") def test_get_city_country_population(self): str = get_city_country(city = "Beijing", country = "China", population = "5000000") self.assertEqual(str, "Beijing, China - 5000000") unittest.main()
结果:
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
11-3 雇员
代码:
import unittest class Employee(): def __init__(self, gname, fname, income): self.gname = gname self.fname = fname self.income = income def give_raise(self, increase = 5000): self.income = self.income + increase class TestEmployee(unittest.TestCase): def setUp(self): self.em = Employee("Ming", "Li", 60000) def test_give_default_raise(self): self.em.give_raise() self.assertEqual(self.em.income, 65000) def test_give_custom_raise(self): self.em.give_raise(10000) self.assertEqual(self.em.income, 70000) unittest.main()
结果:
..
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK