Python 单元测试模拟

标签 python unit-testing mocking

如果你看过我的其他问题,你就会知道我目前在 Python 中的单元测试方面遇到了非常困难的时期。经过两天的努力,我没有取得任何进展。

在我的方法(属于类的一部分)中,有多次对 DAL 的调用。

car_registration = self.dal.cars.get_by_registration('121D121')

此 DAL 在基类中配置。我想在运行单元测试时完全覆盖/模拟这些调用,而是返回预定义的响应,以便我可以继续使用该方法并确保一切按预期工作。

该方法开始于:

def change_registration(self):

    body = json.loads(self.request.body)
    registration = body['registration']
    car = self.dal.cars.get_by_registration(registration)

我目前的Python测试文件是:

class CarTestCase(unittest.TestCase):
     def setUp(self):
         self.car_controller = CarController()


     def test_change_registrations(self):
         self.car_controller.dal.cars.get_by_registration = MagicMock(return_value=3)
         response = self.car_controller.change_registration()

我期待得到响应 3。但是,抛出了一个错误。

AttributeError: 'CarController' object has no attribute '_py_object'

看来模拟不起作用,并且它仍在尝试使用主 DAL,而在使用单元测试时该 DAL 尚未完全设置。如何防止它寻找实际的 DAL 而不是模拟?

最佳答案

我认为您没有向我们展示触发错误的代码,因为您的策略没有任何问题。使用一些想象力来模仿我们没有的代码我可以编写这个并且它运行没有问题:

import unittest
from unittest.mock import MagicMock

class CarList():
    def get_by_registration(self, registration):
        pass

class Dal:
    def __init__(self):
        self.cars = CarList() 
    pass

class CarController:

    def __init__(self):
        self.dal = Dal()

    def change_registration(self):
        registration = None
        car = self.dal.cars.get_by_registration(registration)
        return car 

class CarTestCase(unittest.TestCase):
     def setUp(self):
         self.car_controller = CarController()


     def test_change_registrations(self):
         self.car_controller.dal.cars.get_by_registration =\
             MagicMock(return_value=3)
         result = self.car_controller.change_registration()
         self.assertEqual(result, 3)

unittest.main()

关于Python 单元测试模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47160594/

相关文章:

python - Sqlalchemy 与 Flask - 已删除的数据仍然显示

unit-testing - 单元测试代码根据今天的日期进行日期处理

c++ - 相当于 boost::test 的 CppUnit 保护器?

c# - 使用 Moq .GetMock 向 Linq 表达式注册 ~1IRepository?

python - 如何对我的单元测试进行有意义的代码覆盖分析?

python - 返回对应于随机整数的给定名称

java - 使用 mongodb 存储库进行单元测试

java - 使用 Mockito 模拟静态方法

reactjs - 如何模拟从另一个文件导入的 jest 函数作为默认值

python - 如何修复 "IndexError: list index out of range"