[英]Unit test - test a method of a class
I created a unit test file for testing the method part_firstname_lastname . 我创建了一个单元测试文件来测试part_firstname_lastname方法。 I'm using PyCharm. 我正在使用PyCharm。 When I run the test_person.py there's no error. 当我运行test_person.py时,没有错误。 The test is a success. 测试是成功的。
When I run the file in the command line by using python test_person.py -v
, the error is : 当我使用python test_person.py -v
在命令行中运行文件时,错误是:
from School.person import Personne ModuleNotFoundError: No module named 'School' Blockquote 从School.person导入Personne ModuleNotFoundError:没有名为“ School” Blockquote的模块
In the pycharm I don't have any errors, the import is good. 在pycharm中,我没有任何错误,导入效果很好。
School is a package inside that I have the file person.py . School是其中的一个包,其中包含文件person.py 。 The file test_person.py is in another package named Unit_Test 文件test_person.py在另一个名为Unit_Test的程序包中
1- How can i solve it ? 1-我该如何解决? 2- Must i use Mock for that ? 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 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()
The correct way is to update the PYTHONPATH to contain the folder containing the School
package. 正确的方法是更新PYTHONPATH以包含包含School
软件包的文件夹。
It can be done at different level: 可以在不同级别上完成:
sys.path
system list directly from the test_person.py
file before importing School
- beware it is a rather intrusive way 在导入School
之前,直接从test_person.py
文件中更改sys.path
系统列表-请注意,这是一种相当侵入性的方法 sys.path
system list from a package containing the test_person.py
. 从包含test_person.py
的包中更改sys.path
系统列表。 It can be a handy way if you always use a full test package 如果您始终使用完整的测试包,这可能是一种便捷的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.