如何避免这种python依赖关系?

如何避免这种python依赖关系?,python,unit-testing,dependencies,Python,Unit Testing,Dependencies,我有一个python Presenter类,它有一个创建不同Presenter类实例的方法: class MainPresenter(object): def showPartNumberSelectionDialog(self, pn): view = self.view.getPartNumberSelectionDialog(pn) dialog = SecondPresenter(self.model, view) dialog.s

我有一个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
,它仍然无法捕获对本地
对话框
实例的调用

因此,我有两个问题:

  • 我如何改变我的方法以使代码更易于测试
  • 测试这样的简单代码块是否被认为是一种良好的做法

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

    通过使用框架,您应该将
    SecondPresenter
    类实例替换为
    Mock
    对象。注意,
    对话框
    实例将是用于替换原始类实例的模拟的返回值。此外,您应该注意,现在我可以猜怎么做,但离最终测试版本不远了:

    @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()
    

    我使用<代码> AutoPoC= Trime< /Cord>只是因为我认为这是一个最佳实践,请查看更多细节。

    您还可以修补
    main.view
    main.model
    以测试代码如何调用
    对话框的构造函数。。。但是你应该使用mock,而不是滥用它,你模仿和修补的东西越多,你的测试就会更多地与代码纠缠在一起



    对于第二个问题,我认为测试这类块也是一种很好的做法,但试着修补和模拟尽可能远的地方,而这正是测试环境中不能使用的:您将有一个更灵活的测试,您可以通过重写更少的测试代码来重构代码。

    您当然可以在这里修补SecondPresenter。