【问题标题】:How to avoid this python dependency?如何避免这种python依赖?
【发布时间】:2016-01-13 04:02:48
【问题描述】:

我有一个 python Presenter 类,它有一个创建不同 Presenter 类的实例的方法:

class MainPresenter(object):
    def showPartNumberSelectionDialog(self, pn):
        view = self.view.getPartNumberSelectionDialog(pn)
        dialog = SecondPresenter(self.model, view)
        dialog.show()

我的意图是为我的应用程序中的每个窗口编写一个单独的 Presenter 类,以保持事情井井有条。不幸的是,我发现很难测试showPartNuberSelectionDialog 方法,尤其是测试dialog.show() 是否被调用,因为实例是在方法调用中创建的。因此,即使我使用 python 的模拟框架修补 SecondPresenter,它仍然无法捕获对本地 dialog 实例的调用。

所以,我有两个问题:

  1. 如何更改我的方法以使此代码更具可测试性?
  2. 测试这样的简单代码块是否被认为是一种好习惯?

【问题讨论】:

  • 你当然可以在这里修补 SecondPresenter。

标签: python unit-testing dependencies


【解决方案1】:

是否可以修补SecondPresenter 并检查您如何调用它以及您的代码是否也调用show()

通过使用mock 框架和patch,您应该将SecondPresenter 类实例替换为Mock 对象。注意dialog 实例将是用于替换原始类实例的模拟的返回值。而且你应该照顾where to patch,现在我只能猜到怎么做,但离最终测试版不远了:

@patch("mainpresentermodule.SecondPresenter", autospec=True)
def test_part_number_selection_dialog(self, mock_second_presenter_class):
    main = MainPresenter()
    main.showPartNumberSelectionDialog(123456)
    dialog = mock_second_presenter_class.return_value
    dialog.show.assert_called_with()

我使用autospec=True 只是因为我认为这是最佳实践,请查看Autospeccing 了解更多详情。

您还可以修补 main.viewmain.model 以测试您的代码如何调用 dialog 的构造函数...但是您应该使用模拟而不是滥用它,模拟和修补更多的东西以及更多的测试会和代码纠缠在一起。


对于第二个问题,我认为测试这些块也是一个很好的实践,但尝试尽可能多地修补和模拟,以及在测试环境中不能使用的东西:你将拥有更灵活的测试和你可以通过重写更少的测试代码来重构你的代码。

【讨论】:

    猜你喜欢
    • 2020-11-11
    • 2016-08-09
    • 2014-12-08
    • 2020-04-06
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多