2016-03-04 89 views
0

使用Python 2.7,和模擬圖書館Python的模擬對象實例化

如何測試某些修補的對象已經使用模擬一些具體的參數初始化?

這裏是一些示例代碼和僞代碼:

unittest.py:

import mock 
@mock.patch('mylib.SomeObject') 
def test_mytest(self, mock_someobject): 
    test1 = mock_someobject.return_value 
    test1 = method_inside_someobject.side_effect = ['something'] 

    mylib.method_to_test() 

    # How can I assert that method_to_test instanced SomeObject with certain arguments? 
    # I further test things with that method_inside_someobject call, no problems there... 

mylib.py:

from someobjectmodule import SomeObject 
def method_to_test(): 
    obj = SomeObject(arg1=val1, arg2=val2, arg3=val3) 
    obj.method_inside_someobject() 

那麼,該如何測試SomeObject與ARG1實例化= val1,arg2 = val2,arg3 = val3?

+1

請問你剛纔['assert_called_with'](https://docs.python.org/3/庫/ unittest.mock.html#unittest.mock.Mock.assert_called_with)? – mgilson

+0

讓我編輯問題以顯示一些示例代碼。我嘗試過assert_called_with,但沒有得到任何結果 –

+0

那裏... @mgilson我添加了一些示例代碼。謝謝! –

回答

3

如果你用模擬替換了一個類,創建一個實例只是另一個調用。斷言正確的參數已通過了這一號召,例如,與mock.assert_called_with()

mock_someobject.assert_called_with(arg1=val1, arg2=val2, arg3=val3) 

爲了說明,我已經更新了你的MCVE到工作示例:

test.py

import mock 
import unittest 

import mylib 


class TestMyLib(unittest.TestCase): 
    @mock.patch('mylib.SomeObject') 
    def test_mytest(self, mock_someobject): 
     mock_instance = mock_someobject.return_value 
     mock_instance.method_inside_someobject.side_effect = ['something'] 

     retval = mylib.method_to_test() 

     mock_someobject.assert_called_with(arg1='foo', arg2='bar', arg3='baz') 
     self.assertEqual(retval, 'something') 


if __name__ == '__main__': 
    unittest.main() 

mylib.py

from someobjectmodule import SomeObject 

def method_to_test(): 
    obj = SomeObject(arg1='foo', arg2='bar', arg3='baz') 
    return obj.method_inside_someobject() 

someobjectmodule.py

class SomeObject(object): 
    def method_inside_someobject(self): 
     return 'The real thing' 

並運行測試:

$ python test.py 
. 
---------------------------------------------------------------------- 
Ran 1 test in 0.001s 

OK 
+0

完全正確,謝謝! –