2017-09-14 18 views
2

현재 Unit 테스트를 Python으로 배우는 방법을 배우고 있으며 Mocking 개념에 대해 소개했습니다. 저는 Python 개발과 함께 TDD 개념을 배우기를 희망하는 초보자 Python 개발자입니다. 기술. 나는 사용자로부터 주어진 입력으로 클래스를 조롱하는 개념을 배우려고 애 쓰고있다. Python unittest.mock documentation. 내가 특정 함수를 조롱하는 방법의 예를 얻을 수 있다면, 나는 정말로 감사 할 것이다. 나는 여기에있는 예제를 사용합니다 : Example QuestionPython에서 사용자 입력 모의 방법

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_year을 시도, calculate_age() 고정.

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