模拟断言类型

时间:2014-07-22 08:23:17

标签: python unit-testing mocking

在我的主要课程中,我有这个代码(这是服务,想要在任何机器上工作,而不仅仅是我工作的地方):

class MainClass:
    service = None
    key = None
    url = None

    def __init__(self, service, key, url, port):
        self.service = service
        self.key = key
        self.url = url
        self.port = port


def deleteMetod(self, room, params=None):

    try:
        if not isinstance(room, str) or (not isinstance(params, MainClass) and params != None):
            raise TypeError
    except TypeError:
        raise TypeError("Parameter 'room' should be a string. Parameter 'params' if there must be an instance of Nuve.")
    else:
        response = self.send('DELETE', None, '/rooms/'+room, params)
        return response

我希望它在单元测试中对此方法执行mock(MainClass)

def test_deleteMetodg_type(self):
    ob = MainClass("1212", "19414", "127.0.0.1", "3000")
    self.assertRaises(TypeError, ob.deleteMetod, [])

我想断言并检查方法的返回类型是否正确。

但是对象Mock()不可能只有断言类型assert_called_with()

如何模拟对象并调用其方法并比较返回的类型?

请寻求帮助/提示。

1 个答案:

答案 0 :(得分:0)

如果你只想测试你的方法在提供不正确的参数时引发TypeError,那么你就不必模拟任何东西。只是调用它(错误地),并断言它引发异常。

顺便说一句,顺便说一下,然后不需要提高然后提高TypeError:

def deleteMetod(self, room, params=None):
    if not isinstance(room, str) or (not isinstance(params, MainClass) and params is not None):
        raise TypeError("Parameter 'room' should be a string. Parameter 'params' if there must be an instance of Nuve.")

    response = self.send('DELETE', None, '/rooms/'+room, params)
    return response

此外,在2.7及更高版本中,有一个更方便的assertRaises语法:

def test_deleteMetodg_type(self):
    ob = MainClass("1212", "19414", "127.0.0.1", "3000")
    with self.assertRaises(TypeError):
        ob.deleteMetod([])