2017-06-21 49 views
1

嗨方法調用第一部分的代碼片段:
模塊A:模擬財產在Python

class Foo: 
     def __init__(symbol): 
     self.last_price = None 
     def get_last_price(self): 
     x = do_some_query_requests() 
     self.last_price = x 

模塊B:

class Bar: 
     def convert(symbol, amount): 
     curr = Foo(symbol) 
     curr.get_last_price() 
     #do some conversion with last_price 
     return converted_stuff 

應該正常工作。 現在我嘗試測試轉換方法。但由於最後的價格在變化,我想嘲笑last_price屬性來檢查轉換是否有效。

我發現了一些關於補丁和Magic Mocks的內容,但我不知道如何模擬一個類的方法的輸出,它不會返回某些東西,而只是改變內部屬性。

有人知道該怎麼做嗎?也許還有其他建議?

我想簡單地返回last_price,但其他一些方法也使用它,所以我不需要每次都調用該函數。

在此先感謝!

回答

0

使用可以直接使用作爲curr.last_price CURR是類Foo的對象

我的代碼片斷: 模塊A:

class Foo: 
    def __init__(self,symbol): 
    self.last_price = None 
    def get_last_price(self): 
    x = do_some_query_requests() 
    self.last_price = x 

模塊B:

class Bar: 
    def convert(symbol, amount): 
    curr = Foo(symbol) 
    curr.get_last_price() 
    print(curr.last_price) //get_last_price updates the last_price 
          //You can use that directly 
    #do some conversion with last_price 
    return converted_stuff 
+0

是這是真的,但單元測試的東西,我沒有訪問該對象,因爲它在該方法中調用。那麼我怎樣才能嘲笑last_price的方式,我可以檢查轉換是否正確? 我的意思是我需要知道最後的價格,這是變化的。最後的價格被稱爲轉換。但要知道轉換是否正常工作,我需要知道last_price,手動轉換並在兩個值相等時斷言。 也許我在想複雜... – sawrz

+0

這可能是有幫助的https://stackoverflow.com/questions/23909692/how-to-unittest-local-variable-in-python –

+0

這也是如此,但它不解決我的問題。我不想檢查局部變量。我只對輸出感興趣。但產出隨着最後價格的變化而變化。我需要以某種方式修復這個變量,以獲得可預測的結果。 這就像我會使用一個隨機數進行一些計算。這是非常難以預料的,但我可以通過修正這個「隨機」數字來檢查計算是否正確。模擬可以做到這一點。問題是,這是一個函數返回一些值,而不是操縱一些對象屬性。 – sawrz