簡體   English   中英

使用Python的UnitTest模擬對象創建新對象

[英]Using Python's UnitTest Mock for a new Object

我正在嘗試學習如何為Python使用Mocks。 但是,我一直在為它的一些基本應用而苦苦掙扎。

假設我要測試的代碼是這樣的:

class ProductionClass:
    def method(self):
        newone=ProductionClass()
        newone.something(1, 2, 3)
    def something(self, a, b, c):
        pass
    def __init__(self):
        print("Test")

它們具有一個方法,該方法只是創建自己的新對象並調用該類的方法。

import unittest
import unittest.mock
from ProductionClass import *
from unittest.mock import *

class TestProduction(unittest.TestCase):
    def test_one(self):

        real = ProductionClass()
        real.something = MagicMock()
        real.method()
        real.something.assert_called_once_with(1, 2, 3)

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

再一次,這是一個非常簡單的UnitTest,基本上是從https://docs.python.org/3/library/unittest.mock-examples.html的 26.5.1.1復制而來。

但是,這將測試是否調用了real.something,而我真正要測試的是是否調用了newone.something。

考慮到稍后我們實際調用method()方法時會創建newone,我該如何使用模擬來測試它?

您可以通過在setUp方法中實例化ProductionClass並在test_one中修補ProductionClass來進行測試,如下所示

import unittest
import ProductionClass
import mock

class TestProduction(unittest.TestCase):
    def setUp(self):
        self.real = ProductionClass.ProductionClass()

    @mock.patch("ProductionClass.ProductionClass")
    def test_one(self, mock1):
        print "From Test : %s " % mock1()
        real = self.real
        real.method()
        mock1().something.assert_called_once_with(1, 2, 3)

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

我剛剛修改了生產類,以表明兩個對象都引用了模擬的相同實例

class ProductionClass:
    def method(self):
        newone=ProductionClass()
        print "From Production class : %s" % newone
        newone.something(1, 2, 3)
    def something(self, a, b, c):
        pass
    def __init__(self):
        print("Test")

輸出:

Testing started at 5:52 PM ...
Test
From Test : <MagicMock name='ProductionClass()' id='4330372048'> 
From Production class : <MagicMock name='ProductionClass()' id='4330372048'>

Process finished with exit code 0

您可以通過查看id來驗證兩個對象都引用了模擬對象的相同實例

PS:在此示例中,我一直在使用模擬軟件包,因此您可能需要使用pip進行安裝。

暫無
暫無

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

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