如何在Python中使用mockito和unittest模拟__init__中的方法调用?

时间:2014-09-01 05:27:36

标签: python unit-testing mocking tdd mockito

第一个问题。

我正在尝试为我的FibonacciNumberCalculatorClient.py文件编写单元测试,并测试它在实例化时实际调用socket.socket(socket.AF_INET, socket.SOCK_STREAM)行。目前我正在使用mockito来模拟socket类。然后我实例化我的客户端,它应该调用socket。

有人可以告诉我为什么verify(mock_socket).socket(any(), any())没有接受方法调用吗?

我看了this answer并且认为我做了类似的事情,但被卡住了。

这些是我的文件:

FibonacciNumberCalculatorClient.py

import socket

HOST = "localhost"
PORT = 8000

class FibonacciNumberCalculatorClient():

    def __init__(self, host, port):
        self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.host = host
        self.port = port

def main():
    client = FibonacciNumberCalculatorClient(HOST, PORT)

if __name__ == '__main__':
    main()

ClientTests.py

from FibonacciNumberCalculatorClient import *
import socket
import unittest
from mockito import *

class ClientTests(unittest.TestCase):

    def test_client_connect_to_host_and_port(self):
        # Set up
        host = "localhost"
        port = 8000
        mock_socket = mock(socket)

        # Exercise
        test_client = FibonacciNumberCalculatorClient(host, port)

        # Verify
        verify(mock_socket).socket(any(), any())
        verify(mock_socket).connect(host, port)


def main():
    unittest.main()

if __name__ == '__main__':
    main()

python ClientTests.py运行时,我得到了这个输出:

F
======================================================================
FAIL: test_client_connect_to_host_and_port (__main__.ClientTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "ClientTests.py", line 18, in test_client_connect_to_host_and_port
    verify(mock_socket).socket(any(), any())
  File "build/bdist.macosx-10.9-intel/egg/mockito/invocation.py", line 111, in __call__
    verification.verify(self, len(matched_invocations))
  File "build/bdist.macosx-10.9-intel/egg/mockito/verification.py", line 63, in verify
    raise VerificationError("\nWanted but not invoked: %s" % (invocation))
VerificationError: 
Wanted but not invoked: socket(<Any: None>, <Any: None>)

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

0 个答案:

没有答案