如何为检查列表中是否存在项的简单if语句创建magic mock



我正在尝试测试我的方法,该方法只检查一个字母是否在字母列表中。如果它在列表a中,那么我将myletter分配给一个名为yes的导入对象;否则,我将myletter分配给一个名为no.的导入对象

我试着用MagicMock为它编写一个测试文件,但由于我对使用mock和MagicMock进行测试的概念还不熟悉,我不知道如何继续。我将感谢任何关于如何继续下去的提示或解决方案。

我应该为每个列表创建一个mock对象,并为myletter创建另一个mock-object来检查这两个mock-objects吗?或者我应该如何继续这样做?

我的代码:

from mydir.newdir import yes
from mydir.newdir import no

def yes_no_det(check_letter: str):

first_list = ['a', 'b', 'c']

second_list = ['d', 'e', 'f']

myletter = None
if check_letter:    
if check_letter in first_list:
myletter = yes.att
elif check_letter in second_list:
myletter = no.att
return myletter

到目前为止我的测试:

import unittest
from mock import MagicMock, patch
class letter_check_test(TestCase):
with patch('mydir.newdir.check_letter_py.yes') as mock_yes,
patch('mydir.newdir.check_letter_py.no') as mock_no:
from mydir.newdir.check_letter_py import yes_no_det
mock_check_letter = MagicMock()
mock_yes = mock_yes.att
mock_no = mock_no.att
def test_check_letter(self):
# I am not sure how further to continue or what to check here

更新了可能正确的测试代码:

class letter_check_test(TestCase):
def test_yes_det():
assert yes_no_det('a') == mydir.newdir.yes
def test_no_det():
assert yes_no_det('f') == mydir.newdir.no
def test_neither_det():
assert yes_no_det('x') == None

谢谢你的回答。如果我需要在不降级或报告的情况下更改/删除此帖子或其他内容,请告诉我。我真的很感激!

在这种情况下,它只是使用了assert或assertequal代码。例如:

class letter_check_testYES(Testing, TestingsCases):
def test_letter_check(self):
with patch('mydir.newdir.check_letter_py.yes') as YES:
from mydir.newdir.check_letter_py import yes_no_det
assert yes_no_det('a') == YES
class letter_check_testNO(Testing, TestingsCases):
def test_letter_check(self):
with patch('mydir.newdir.check_letter_py.no') as NO:
from mydir.newdir.check_letter_py import yes_no_det
assert yes_no_det('f') == YES
class letter_check_test(Testing, TestingsCases):
from mydir.newdir.check_letter_py import yes_no_det
assert yes_no_det('f') == NONE

相关内容

  • 没有找到相关文章

最新更新