2017-09-14 156 views
2

我目前正在嘗試學習如何使用Python進行單元測試,並將其引入到Mocking的概念中,我是一位初學Python開發人員,希望能夠學習TDD的概念以及我的Python開發技能。我正在努力學習用給定的輸入嘲笑一個類的概念,如果我能得到一個我將如何模擬某個函數的例子,我會非常感激。我會用在這裏找到了例子:Example Question如何在Python中模擬用戶輸入

class AgeCalculator(self): 

    def calculate_age(self): 
     age = input("What is your age?") 
     age = int(age) 
     print("Your age is:", age) 
     return age 

    def calculate_year(self, age) 
     current_year = time.strftime("%Y") 
     current_year = int(current_year) 
     calculated_date = (current_year - age) + 100 
     print("You will be 100 in", calculated_date) 
     return calculated_date 

使用誚年齡自動輸入,這樣它會返回該mock'ed年齡是100年請人可以創造我的一個例子單元測試。

謝謝。

+0

我認爲你最好將計算與用戶界面分開。計算然後變得非常容易進行單元測試。 –

回答

0

這裏 - 我修正了calculate_age(),你試試`calculate_year。

class AgeCalculator: #No arg needed to write this simple class 

     def calculate_age(): # Check your sample code, no 'self' arg needed 
      #age = input("What is your age?") #Can't use for testing 
      print ('What is your age?') #Can use for testing 
      age = '9' # Here is where I put in a test age, substitutes for User Imput 
      age = int(age) 
      print("Your age is:", age) 
      #return age -- Also this is not needed for this simple function 

     def calculate_year(age): # Again, no 'Self' arg needed - I cleaned up your top function, you try to fix this one using my example 
      current_year = time.strftime("%Y") 
      current_year = int(current_year) 
      calculated_date = (current_year - age) + 100 
      print("You will be 100 in", calculated_date) 
      return calculated_date 


    AgeCalculator.calculate_age() 

從我在你的代碼中看到,你應該看看了如何建立功能 - 請不要採取的是進攻的方式。你也可以通過手動測試你的功能。正如你的代碼所代表的那樣,它不會運行。

祝你好運!

-1

你不模擬輸入,但功能。在這裏,嘲笑input基本上是最容易做的事情。

from unittest.mock import patch 

@patch('yourmodule.input') 
def test(mock_input): 
    mock_input.return_value = 100 
    # Your test goes here 
0

您可以模擬Python3.x中的buildins.input方法,並使用with語句來控制嘲笑期的範圍。

import unittest.mock 
def test_input_mocking(): 
    with unittest.mock.patch('builtins.input', return_value=100): 
     xxx