2015-06-30 53 views
3

我想要一個單元測試來聲明一個函數內的變量action被設置爲它的期望值,這個變量被使用的唯一時間是當它在一個調用中傳遞時到圖書館。Python單元測試模擬,得到模擬函數的輸入參數

Class Monolith(object): 
    def foo(self, raw_event): 
     action = # ... Parse Event 
     # Middle of function 
     lib.event.Event(METADATA, action) 
     # Continue on to use the build event. 

我的想法是,我可以嘲笑lib.event.Event,並獲取其輸入參數,並聲稱他們的具體數值。

>這是不是嘲笑工作?模擬文檔使我感到沮喪,因爲它的不一致性,半範例和與我想要做的事無關的很多例子。

+0

其中具有u使用模擬?你可以模擬'lib.event.Event'並聲明 – vks

回答

3

你可以使用貼片裝飾,然後調用assert_called_with到像這樣的嘲笑對象:

如果你有這樣的結構:

example.py 
tests.py 
lib/__init__.py 
lib/event.py 

而且example.py是內容:

import lib 

METADATA = 'metadata_example' 

class Monolith(object): 

    def foo(self, raw_event): 
     action = 'action_example' # ... Parse Event 
     # Middle of function 
     lib.event.Event(METADATA, action) 
     # Continue on to use the build event. 

lib中的內容/ event.py是:

class Event(object): 

    def __init__(self, metadata, action): 
     pass 

tests.py的代碼應該是這樣的:

import mock 
import unittest 

from lib.event import Event 
from example import Monolith 


class TestExample(unittest.TestCase): 

    @mock.patch('lib.event.Event') 
    def test_example1(self, event_mocked): 
     # Setup 
     m = Monolith() 

     # Exercise 
     m.foo('raw_event') 

     # Verify 
     event_mocked.assert_called_with('metadata_example', 'action_example') 
+0

如果我想將傳遞給模擬的參數作爲一個字典呢? – dopatraman

+3

@dopatraman您可以使用['call_args'](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.call_args)或['call_args_list'](https: //docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.call_args_list)。 –