单元测试 - 测试一个class的方法

Unit test - test a method of a class

我创建了一个单元测试文件来测试方法 part_firstname_lastname。我正在使用 PyCharm。当我 运行 时 test_person.py 没有错误。测试成功。

当我在命令行中使用python test_person.py -v运行文件时,错误是:

from School.person import Personne ModuleNotFoundError: No module named '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 包的文件夹。

可以在不同级别完成:

  • 在实际启动测试的工具或框架中(这就是 PyCharm 的工作方式)
  • 在执行测试之前从命令行更改 PYTHONPATH 环境变量(语法将取决于 OS 和 shell)
  • 在导入之前直接从 test_person.py 文件更改 sys.path 系统列表 School - 请注意这是一种相当侵入性的方式
  • 从包含 test_person.py 的包中更改 sys.path 系统列表。如果你总是使用完整的测试包,这可能是一个方便的方法