[英]Unit test - test a method of a class
我創建了一個單元測試文件來測試part_firstname_lastname方法。 我正在使用PyCharm。 當我運行test_person.py時,沒有錯誤。 測試是成功的。
當我使用python test_person.py -v
在命令行中運行文件時,錯誤是:
從School.person導入Personne ModuleNotFoundError:沒有名為“ School” Blockquote的模塊
在pycharm中,我沒有任何錯誤,導入效果很好。
School是其中的一個包,其中包含文件person.py 。 文件test_person.py在另一個名為Unit_Test的程序包中
1-我該如何解決? 2-我必須為此使用Mock嗎?
class Person:
def __init__(self, first, last):
self.__code = 0
self.__firstname = first
self.__lastname = last
def __str__(self):
return self.firstname + ' ' + self.lastname
@property
def firstname(self):
return self.__firstname
@firstname.setter
def firstname(self, value):
self.__firstname = value
@property
def lastname(self):
return self.__lastname
@lastname.setter
def lastname(self, value):
self.__lastname = value
@staticmethod
def part_firstname_lastname(data):
"""
This method take a part of the data
@param : str : data
:return: str : part of the data entered
"""
if len(data) > 3:
return data[0:3].upper()
return data[0:1].upper()
test_person.py
import unittest
from School.person import Person
class test_person(unittest.TestCase):
def test_code_personne(self):
p1 = Personne('Callier', 'John')
p1.part_firstname_lastname(p1.firstname)
self.assertEqual(p1.part_firstname_lastname(p1.firstname), 'CAD')
if __name__ == '__main__':
unittest.main()
正確的方法是更新PYTHONPATH以包含包含School
軟件包的文件夾。
可以在不同級別上完成:
School
之前,直接從test_person.py
文件中更改sys.path
系統列表-請注意,這是一種相當侵入性的方法 test_person.py
的包中更改sys.path
系統列表。 如果您始終使用完整的測試包,這可能是一種便捷的方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.