2017-09-14 160 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