我們的測試范例完全變化了. 現在我們可以核實(shí)并驗證方法的內部功能是否有任何副作用.
將刪除功能作為服務(wù)
到目前為止,我們只是對函數功能提供模擬測試,并沒(méi)對需要傳遞參數的對象和實(shí)例的方法進(jìn)行模擬測試。接下來(lái)我們將介紹如何對對象的方法進(jìn)行模擬測試。
首先,我們先將rm方法重構成一個(gè)服務(wù)類(lèi)。實(shí)際上將這樣一個(gè)簡(jiǎn)單的函數轉換成一個(gè)對象并不需要做太多的調整,但它能夠幫助我們了解mock的關(guān)鍵概念。下面是重構的代碼:
1 2 3 4 5 6 7 8 9 10 11 12 |
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import os.path class RemovalService(object): """A service for removing objects from the filesystem.""" def rm(filename): if os.path.isfile(filename): os.remove(filename) |
你可以發(fā)現我們的測試用例實(shí)際上沒(méi)有做太多的改變:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#!/usr/bin/env python # -*- coding: utf-8 -*- from mymodule import RemovalService import mock import unittestclass RemovalServiceTestCase(unittest.TestCase): @mock.patch('mymodule.os.path') @mock.patch('mymodule.os') def test_rm(self, mock_os, mock_path): # instantiate our service reference = RemovalService() # set up the mock mock_path.isfile.return_value = False reference.rm("any path") # test that the remove call was NOT called. self.assertFalse(mock_os.remove.called, "Failed to not remove the file if not present.") # make the file 'exist' mock_path.isfile.return_value = True reference.rm("any path") mock_os.remove.assert_called_with("any path") |
原文轉自:http://www.diggerplus.org/archives/2704