与Python Unittest模拟的另一堂课的模拟方法

发布于 2025-02-04 21:09:34 字数 863 浏览 1 评论 0原文

我有一个课程,在该类中,有其他类别的方法。假设看起来像这样(只是一个例子):

from jobs.fruit import Fruit
from jobs.veggie import Veggie

class Healthy:
    def start(self, arg):
        self.start_connection()
        if len(arg) == 1 or self.check(arg):
            fruit = Fruit()
            fruit.start()
            return 1
        else:
            veggie = Veggie()
            veggie.update()
            return 0

我正在为我的健康课程编写单元测试,而开始看起来像这样:

def test_start():
    healthy = Healthy()
    healthy.start_connection = MagicMock(return_value=1)
    healthy.check = MagicMock(return_value=True)
    fruit = Fruit()
    fruit.start = MagicMock(return_value = 0)
    result = healthy.start()

不幸的是,在进行测试时,它不会取得成果。运行原始方法。我应该如何模拟该类或方法并将该信息传递给我正在测试的方法?我从来不必嘲笑我正在测试的班级外的东西,并有点困扰它。我宁愿坚持使用Unitest Mock,以免弄乱代码中的几种方法,因此对于我的同事来说很明显。提前致谢!

I have a class and within that class there are used methods from another classes. Let's say it looks like that (just an example):

from jobs.fruit import Fruit
from jobs.veggie import Veggie

class Healthy:
    def start(self, arg):
        self.start_connection()
        if len(arg) == 1 or self.check(arg):
            fruit = Fruit()
            fruit.start()
            return 1
        else:
            veggie = Veggie()
            veggie.update()
            return 0

I'm writting unit tests for my Healthy class, and the start looks like this:

def test_start():
    healthy = Healthy()
    healthy.start_connection = MagicMock(return_value=1)
    healthy.check = MagicMock(return_value=True)
    fruit = Fruit()
    fruit.start = MagicMock(return_value = 0)
    result = healthy.start()

Unfortunately when running the test it doesn't take fruit.start mocked value, but it tries to run original method. How should I mock that class or method and pass that info to the method that I'm testing? I never had to mock something from outside the class that I'm testing and got a bit stuck with it. I'd prefer to stick to unittest mock to not mess with several methods in the code so it's clear for my coworkers. Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文