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

2024-05-29 07:50:31 发布

您现在位置:Python中文网/ 问答频道 /正文

有史以来第一个问题。在

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

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

我看着this answer,以为我在做类似的事情,但被卡住了。在

这些是我的档案:

腓肠肌mberCalculatorClient.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()

在客户端测试.py在

^{pr2}$

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)

Tags: inpytestselfclienthostmainport

热门问题