gpt4 book ai didi

python - 如何为单元测试期间调用的方法提供默认返回值? - Python

转载 作者:太空宇宙 更新时间:2023-11-03 11:08:50 25 4
gpt4 key购买 nike

这是一个简化我所拥有的示例类:

class.py

class MyClass(object):

@staticmethod
def getDictionary():
#some calculations, returns a dictionary

def checkConfiguration(self):
#some code
self.getDictionary()
#some other code
return value

现在我正在为 checkConfiguration 进行单元测试:

classTest.py

import class
import unittest

class TestMyClass(unittest.TestCase):

def setUp(self):
self.classTest = class.MyClass()

def test_CheckConfiguration(self):
#What to put here?

原来的CheckConfiguration调用getDictionary。有没有办法告诉 test_CheckConfiguration(self) 如果调用 getDictionary,它应该自动返回我可以输入的字典?像这样的东西:

    def test_CheckConfiguration(self):
if method getDictionary is called:
return {'a':123, 'b':22}
checkValue = self.classTest.checkConfiguration()

我知道这在 Java 中是可能的,尽管我在这方面和这方面都没有足够的经验。谢谢。

最佳答案

我认为您需要一个模拟框架。我建议 PyMock .

以下是您可以如何使用它:

classTest.py

import class
import pymock
import unittest

class TestMyClass(pymock.PyMockTestCase):

def setUp(self):
self.classTest = class.MyClass()

def test_CheckConfiguration(self):
self.override(self.classTest, 'getDictionary')
pymock.expectAndReturn(self.classTest.getDictionary(), {'a':123, 'b':22})
self.replay()
checkValue = self.classTest.checkConfiguration()
self.verify()

关于python - 如何为单元测试期间调用的方法提供默认返回值? - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11640226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com