【发布时间】:2008-10-21 23:04:33
【问题描述】:
在我的问题As a “mockist” TDD practitioner, should I mock other methods in the same class as the method under test?、Avdi 中回答“我个人认为嘲笑自我几乎总是一种代码味道。它是在测试实现而不是行为。”他可能是对的,但我常常无法区分实现和行为。
我有另一个示例(Python 风格的伪代码)可能会带来有用的答案:
class Consumer:
def spec_dirpath:
client = VCS.get_connection(self.vcs_client_name)
client.sync()
return client.dirpath()
def spec_filepath:
filepath = os.path.join(spec_dirpath(), self.spec_filename)
if not os.path.exists(filepath):
raise ConsumerException
return filepath
def get_components:
return Components.get_components_from_spec_file(self.spec_filepath())
这里的想法是 get_components 方法调用 spec_filepath 方法以获取 get_components_from_spec_file Components 类方法将从中读取组件列表的文件的路径。 spec_filepath 方法依次调用spec_dirpath,它从VCS 系统同步包含spec 文件的目录并返回该目录的路径。 (尽量不要在这段代码中寻找错误——毕竟它是伪代码。)
我正在寻找有关如何测试这些方法的建议...
测试 spec_dirpath 应该非常简单。我可以模拟 VCS 类并让它返回一个模拟对象并确认调用了适当的方法(并且 spec_dirpath 方法返回模拟的 dirpath 方法返回的内容)。
但是如果我在测试 spec_filepath 时不模拟 spec_dirpath,如何避免在 spec_filepath 测试中从 spec_dirpath 代码中复制相同的测试代码?如果我在测试 get_components 时不模拟 spec_filepath,如何避免从 spec_filepath 和 spec_dirpath 中复制测试代码?
【问题讨论】:
标签: unit-testing mocking code-duplication