0
点赞
收藏
分享

微信扫一扫

Python单元测试-Unittest(三)

梅梅的时光 2022-03-25 阅读 92

两个比较常用的test fixture,它们分别是:

  • setUp
  • tearDown

其中setUp是每个测试方法执行之前需要被提前执行的方法。而相反tearDown方法是每个方法执行之后需要被执行。它们是非常有必要的,特别是当我们的测试需要一些前置或者后置动作需要执行时,它提高了代码的重用度和让代码结构更简洁,清晰。
以一个简单的案例来说明其用法。首先准备代码,文件名称为apple.py具体如下:

class Apple():
    def __init__(self):
        self._quantity = 200
    
    def quantity(self):
        return self._quantity
    

    def re_fill(self,number):
        self._quantity = number

其次准备测试代码,文件名为test_apple.py,具体如下。其他包含了测试函数和setUp、tearDown函数。

import unittest
from apple import Apple

class AppleTestCases(unittest.TestCase):
    def setUp(self):
        self.apple = Apple()
    
    def test_default_apple_quantity(self):
        self.assertEqual(self.apple.quantity(),200,'default quantity is wrong.')
    
    def test_re_fill_quantity(self):
        self.apple.re_fill(500)
        self.assertEqual(self.apple.quantity(),500,'wrong quantity after re-fill.')
    
    def tearDown(self):
        print("The testing is done.")

通过如下执行命令:

python -m unittest discover -p  "test_apple.py" -v

执行结果如下:
在这里插入图片描述

从上可以得出setUp和tearDown似乎是一对儿,如果存在的话,总是同时出现。那么如果setUp函数出现了错误或异常,那么tearDown还会再像往常那样执行么?
还是从实际案例中找答案吧。对测试代码微调,代码如下,在setUp函数中添加了一行抛出异常代码"raise Exception(“This is an exception!!!”)"

import unittest
from apple import Apple

class AppleTestCases(unittest.TestCase):
    def setUp(self):
        self.apple = Apple()
        raise Exception("This is an exception!!!")
    
    def test_default_apple_quantity(self):
        self.assertEqual(self.apple.quantity(),200,'default quantity is wrong.')
    
    def test_re_fill_quantity(self):
        self.apple.re_fill(500)
        self.assertEqual(self.apple.quantity(),500,'wrong quantity after re-fill.')
    
    def tearDown(self):
        print("The testing is done.")
举报

相关推荐

0 条评论