如何测试第三方库的包装?

时间:2018-11-01 03:15:17

标签: python unit-testing mocking publish-subscribe gcloud

class GPublisher():

    def __init__(self, topic_name):
        self.publisher = PublisherClient()
        self.project_id = settings.project_id
        self.topic_path = self.publisher.topic_path(
            self.project_id, topic_name)

    def publish(self, data):
        message_future = self.publisher.publish(self.topic_path, data=data)
        message_future.add_done_callback(self.callback)

    def callback(self, message_future):
        if message_future.exception(timeout=30):
            print('Publishing message on {} threw an Exception {}.'.format(
                self.topic_name, message_future.exception()))
        else:
            print(message_future.result())

如何为该课程做单元测试?以及如何确保该类不是真正的类,因此始终确保其正常运行?

1 个答案:

答案 0 :(得分:0)

如果您注入依赖项,则可以轻松地将第三方模块替换为模拟单元测试

class GPublisher():

def __init__(self, topic_name, publisher_client):
    self.publisher = publisher_client
    self.project_id = settings.project_id
    self.topic_path = self.publisher.topic_path(
        self.project_id, topic_name)

并在单元测试中

GPublisher("topic_name", mock_publish_client)