Unit_test一种调用单元测试不知道的另一种方法的方法

时间:2017-01-05 14:17:36

标签: python unit-testing

您如何测试调用另一种方法的简单方法?我现在正试图测试wssender方法。

in worker.py
---------------- 
class Worker(self):
    def __init__(self, ws)
        self.ws = ws

    def wssender(self,str):
        newstr = '<br>{0}'.format(str)
        self.ws.sendMessage(newstr.encode())

和测试代码

in unit_test.py
-----------------
class SimpleTest(unittest.TestCase):
    def test_wssender(self):
        msg = 'test send message'
        wss=worker.Worker
        wss.wssender(wss, msg)
        expected = "<br>test send message"
        self.assertEqual(<something>, expected)

有两个问题。在运行此测试时,我得到了。 (ws是一个Web套接字)

AttributeError: type object 'Worker' has no attribute 'ws'

和 wssender没有返回任何内容,因此我不确定在这种情况下要测试什么。

2 个答案:

答案 0 :(得分:1)

这是怎么回事?

import unittest
from unittest.mock import MagicMock

class Worker(object):
    def __init__(self, ws):
        self.ws = ws

    def wssender(self, str):
        newstr = '<br>{0}'.format(str)
        self.ws.sendMessage(newstr.encode())

class WorkerTests(unittest.TestCase):
    def test_wssender(self):
        # Arrange
        ws = MagicMock()
        ws.sendMessage = MagicMock()
        worker = Worker(ws)

        # Act
        worker.wssender('test send message')

        # Assert
        ws.sendMessage.assert_called_once_with(b'<br>test send message')

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

<强>输出

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

OK

答案 1 :(得分:1)

我认为“班工(自我)”是一个错字,而且它真的是“班工(对象)”(或任何其他基类)。

wrt /第一期,您忘了在测试中实现Worker - 您想要:

ws = WhateverWsIsSupposedToBe()
wss=worker.Worker(ws)
wss.wssender(msg)

完全不相关,但wssender()不是方法的好名字 - sender是中午,方法是动作,应该使用动词,所以wssend()(或只是{{1} FWIW)会更好。

现在有了第二个问题,你有两个选择。如果您要测试的是消息格式,请将其拆分为另一种方法:

send()

现在您可以单独测试class Worker(object): def __init__(self, ws) self.ws = ws def prepare(self, msg): return '<br>{0}'.format(msg).encode(...) def send(self, msg): self.ws.sendMessage(self.prepare(msg))

如果您要测试Worker.prepare(msg)调用Worker.send(msg)(并使用预期参数调用它),则必须模拟self.ws.sendMessage(...)。您可以手动执行此操作:

ws

或者您可以使用 class MockWs(object): def __init__(self): self.msg = None def sendMessage(self, msg): self.msg = msg class SimpleTest(unittest.TestCase): def test_send(self): ws = MockWs() msg = 'test send message' wss=worker.Worker(ws) wss.send(msg) expected = "<br>test send message" self.assertEqual(ws.msg, expected) 库,参见Tacg的答案。