与Python Unittest模拟的另一堂课的模拟方法
我有一个课程,在该类中,有其他类别的方法。假设看起来像这样(只是一个例子):
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论