簡體   English   中英

單元測試-測試類的方法

[英]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軟件包的文件夾。

可以在不同級別上完成:

  • 在將實際啟動測試的工具或框架中(PyCharm的工作方式)
  • 在執行測試之前,從命令行更改PYTHONPATH環境變量(語法取決於操作系統和外殼程序)
  • 在導入School之前,直接從test_person.py文件中更改sys.path系統列表-請注意,這是一種相當侵入性的方法
  • 從包含test_person.py的包中更改sys.path系統列表。 如果您始終使用完整的測試包,這可能是一種便捷的方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM