gpt4 book ai didi

python - 测试 GUI 代码 : should I use a mocking library?

转载 作者:太空狗 更新时间:2023-10-30 01:30:42 24 4
gpt4 key购买 nike

最近,我在用 Python 开发 GUI 应用程序时一直在试验 TDD。我发现通过测试来验证我的代码的功能是非常令人放心的,但是要遵循 TDD 的一些推荐实践是很棘手的。也就是说,首先编写测试一直很困难。而且我发现很难使我的测试可读(由于大量使用模拟库)。

我选择了一个名为 mocker 的模拟库.我经常使用它,因为我正在测试的大部分代码都会调用 (a) 我的应用程序中依赖于系统状态的其他方法或 (b) 没有事件循环就无法存在的 ObjC/Cocoa 对象,等等。

无论如何,我有很多这样的测试:

def test_current_window_controller():
def test(config):
ac = AppController()
m = Mocker()
ac.iter_window_controllers = iwc = m.replace(ac.iter_window_controllers)
expect(iwc()).result(iter(config))
with m:
result = ac.current_window_controller()
assert result == (config[0] if config else None)
yield test, []
yield test, [0]
yield test, [1, 0]

请注意,这实际上是三个测试;都使用相同的参数化测试函数。这是正在测试的代码:

def current_window_controller(self):
try:
# iter_window_controllers() iterates in z-order starting
# with the controller of the top-most window
# assumption: the top-most window is the "current" one
wc = self.iter_window_controllers().next()
except StopIteration:
return None
return wc

我在使用 mocker 时注意到的一件事是,首先编写应用程序代码然后再返回并编写测试会更容易,因为大多数时候我都在模拟许多方法调用和语法编写模拟调用比应用程序代码更冗长(因此更难编写)。编写应用程序代码然后从中建模测试代码会更容易。

我发现使用这种测试方法(以及一些纪律)我可以轻松编写具有 100% 测试覆盖率的代码。

我想知道这些测试是否是好的测试?当我最终发现编写好的测试的秘诀时,我会后悔这样做吗?

我是否违反了 TDD 的核心原则以至于我的测试是徒劳的?

最佳答案

如果您在编写代码并使它们通过后才编写测试,那么您就不是在进行 TDD(您也不会从测试优先或测试驱动开发中获得任何好处。 . 查看有关 TDD 权威书籍的 SO 问题)

One of the things I've noticed with using mocker is that it's easier to write the application code first and then go back and write the tests second, since most of the time I'm mocking many method calls and the syntax to write the mocked calls is much more verbose (thus harder to write) than the application code. It's easier to write the app code and then model the test code off of that.

当然,这更容易,因为您只是在通过使用特定类型的画笔将其绘制为橙色后测试天空是否为橙色。这是 retrofit 测试(为了 self 保证)。模拟很好,但你应该知道如何以及何时使用它们——就像俗话说的那样“当你有一把锤子时,一切看起来都像钉子”也很容易写出一大堆难以阅读且没有帮助的东西- 是测试。花在理解测试内容上的时间是浪费的时间,可以用来修复损坏的时间。

重点是:

  • 阅读Mocks aren't stubs - Martin Fowler如果你还没有。用谷歌搜索出一些记录好的实例 ModelViewPresenter图案化的 GUI(如有必要,伪造/模拟 UI)。
  • 研究您的选择并做出明智的选择。我会扮演那个在你左肩上有光环的人,穿着白色的衣服说“不要这样做”。阅读关于 my reasons 的问题- 圣贾斯汀在你的右肩上。我相信他也有话要说:)

关于python - 测试 GUI 代码 : should I use a mocking library?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/79454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com