0

我有一个UUT实例化Worker对象并调用它们的do_stuff()方法的类。对象将
对象用于两件事: WorkerProvider

  1. 调用提供者对象上的方法来做一些事情
  2. 通过订阅提供程序事件的方法从提供程序获取通知

当工作人员收到通知时,它会处理它,并通知UUT对象,作为响应,它可以创建更多Worker对象。

我已经单独测试了每个类,我想一起测试UUT+ Worker。为此,我打算模拟Provider.

import mock
import unittest
import provider

class Worker():
    def __init__(self, *args):
        resource.default_resource.subscribe('on_spam', self._on_spam) # I'm going to patch 'resource.default_resource'

    def do_stuff(self):
        self.resource.do_stuff()

    def _on_spam(self, message):
        self._tell_uut_to_create_more_workers(message['num_of_new_workers_to_create'])


class UUT():
    def __init__(self, *args):
        self._workers = []

    def gen_worker_and_do_stuff(self, *args)
       worker = Worker(*args)
       self._workers.append(resource)
       worker.do_stuff()


class TestCase1(unittest.TestCase):

    @mock.patch('resource.default_resource', spec_set=resource.Resource)
    def test_1(self, mock_resource):
        uut = UUT()
        uut.gen_worker_and_do_stuff('Egg')   # <-- say I automagically grabbed the resulting Worker into self.workers
        self.workers[0]._on_spam({'num_of_new_workers_to_create':5}) # <-- I also want to get hold of the newly-created workers

有没有办法获取由 生成的工作对象uut,而不直接访问其中的_workers列表uut(这是一个实现细节)?

我想我可以在Worker.__init__工作人员订阅提供程序事件的地方做到这一点,所以我想问题可以简化为:
如何self在调用时提取被调用方中的resource.default_resource.subscribe('on_spam', self._on_spam)

4

1 回答 1

-1

As an application of the Dependency Inversion principle, I'd pass the Worker class as a dependency to UUT:

class UUT():
    def __init__(self, make_worker=Worker):
        self._workers = []
        self._make_worker = make_worker

    def gen_worker_and_connect(self, *args)
       worker = self._make_worker(*args)
       self._workers.append(resource)
       worker.connect()           

Then provide anything you want from the test instead of Worker. This own function could share the created object with the test scope. Besides solving this particular problem, that would also make the dependency explicit and independent of the UUT implementation. And you would not need to mock the resource thing as well, which makes the test dependent on things unrelated to the class under test.

于 2012-05-29T14:07:43.133 回答