亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

具有模擬和多個功能的單元測試

具有模擬和多個功能的單元測試

絕地無雙 2023-05-09 15:32:49
我不能實例化一個對象,因為它是一個抽象類,所以我必須使用模擬來測試我的代碼。有人告訴我,最好通過創建一個新mock類來完成。class MockMyClass(MyClass):     def my_first_function(...):這個想法是我然后實例化一個MockMyClass對象,我可以在其中測試私有函數。我已經閱讀了 python指南并研究了其他堆棧問題。到這里,mock背后的理論已經很好的解釋了。不幸的是,我仍然不知道如何在大型單元測試中為多個函數使用模擬。例如:如果我有一個類,主代碼中的其他類從中繼承函數。這可以采用以下形式:class SharedFunctions(AnotherClass):    first_function():        #do some important calculations to generate stuff.#        self.stuff = first_function_attribute_stuff        return returned_first_stuff    second_functions(returned_stuff)        returned_second_stuff = self.stuff + returned_first_stuff                return returned_second_stuff并且該類SharedFunctions還繼承自另一個類(注意抽象方法)的形式:class AnotherClass():    @abc.abstractmethod    def one_important_universal_function(...):        pass我試圖unittest為SharedFunctions這段代碼構建一個。到目前為止,這是我嘗試過的:class MockSharedFunctions(SharedFunctions):    def first_function(...):        self.stuff = some value        returned_first_stuff = given some other value        return returned_first_stuff    def second_function        returned_second_stuff = another value.        return returned_second_stuffclass TestSharedFunctions(unittest.TestCase):    def test_first_function(self):        # insert code #        self.assertTrue(True)    def test_second_function(self):        # insert code #        self.assetEqual(output, expected)        self.assertTrue(True)if __name__ == "__main__":    unittest.main()insert code使用模擬的各種嘗試在哪里。但是,我還沒有找到一個清楚的例子來說明如何使用模擬函數來替換其他函數,或者確認這會起作用。感謝您的任何幫助。
查看完整描述

1 回答

?
神不在的星期二

TA貢獻1963條經驗 獲得超6個贊

一個常見的問題是模擬函數的使用過于復雜。您幾乎可以像對待另一個類方法一樣對待它們。在您的情況下,abstractmethod裝飾器可能會造成混亂。


這接近您可能需要的東西。


class MockSharedFunctions(SharedFunctions):

    def one_important_universal_function(**args):

        return 0


class TestSharedFunctions(unittest.TestCase):

    def test_first_function(self):

        mock = MockSharedFunctions()

        mock_output = firstfunction(**args)

        mock_stuff = mock.stuff


        self.assertTrue(True)

        self.assetEqual(mock_output, expected)

        self.assetEqual(mock_stuff, expected)


    def test_second_function(self):

        mock = MockSharedFunctions()

        mock.stuff = some_value

        mock_output = second_function(**args)


        self.assetEqual(mock_output, expected)

        self.assertTrue(True)


if __name__ == "__main__":

    unittest.main()

在這里,MockSharedFunctions您已經在繼承SharedFunctions. 作為one_important_universal_function一個抽象方法,它需要被定義。


查看完整回答
反對 回復 2023-05-09
  • 1 回答
  • 0 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號