簡體   English   中英

魔術模擬 assert_Called_once 與 assert_Called_once_with 奇怪的行為

[英]Magic mock assert_called_once vs assert_called_once_with weird behaviour

我注意到在 python 中使用assert_called_onceassert_called_once_with有一個奇怪的行為。 這是我真正的簡單測試:

文件模塊/a.py

from .b import B

class A(object):
    def __init__(self):
        self.b = B("hi")

    def call_b_hello(self):
        print(self.b.hello())

文件模塊/b.py

class B(object):
    def __init__(self, string):
        print("created B")
        self.string = string;

    def hello(self):
        return self.string

這些是我的測試:

import unittest
from mock import patch
from module.a import A    

class MCVETests(unittest.TestCase):
    @patch('module.a.B')   
    def testAcallBwithMockPassCorrect(self, b1):
        a = A()
        b1.assert_called_once_with("hi")
        a.call_b_hello()
        a.b.hello.assert_called_once()

    @patch('module.a.B')
    def testAcallBwithMockPassCorrectWith(self, b1):
        a = A()
        b1.assert_called_once_with("hi")
        a.call_b_hello()
        a.b.hello.assert_called_once_with()

    @patch('module.a.B')
    def testAcallBwithMockFailCorrectWith(self, b1):
        a = A()
        b1.assert_called_once_with("hi")
        a.b.hello.assert_called_once_with()

    @patch('module.a.B')
    def testAcallBwithMockPassWrong(self, b1):
        a = A()
        b1.assert_called_once_with("hi")
        a.b.hello.assert_called_once()

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

我在函數名稱中提到的問題是:

  • 測試 1 正確通過
  • 測試 2 正確通過
  • 測試 3 正確失敗(我已刪除對 b 的調用)
  • 測試 4 通過我不知道為什么。

難道我做錯了什么? 我不確定,但閱讀文檔docs python

assert_Called_once(*args, **kwargs)

斷言模擬只被調用了一次。

這是舊的,但對於其他登陸這里的人......

對於 python < 3.6, assert_called_once不是一回事,所以你實際上是在做一個不會出錯的assert_called_once函數調用

請參閱: http : //engineroom.trackmaven.com/blog/mocking-mistakes/

您可以改為檢查呼叫計數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM