我已经编写了一个可以使用不同存储后端的存储接口。作为演示,我编写了一个实现,将对象存储为标准Python字典中的键/值对。
class MyStorageInterface(object):
def store(self, key, value):
raise NotImplementedError("Class must be subclassed")
def get(self, key):
raise NotImplementedError("Class must be subclassed")
# Example implementation
class DictStorage(MyStorageInterface):
def __init__(self):
self._cache = dict()
def store(self, key, value):
self._cache[key] = value
def get(self, key):
return self._cache[key]
现在,我想为我的DictStorage
实现编写一些单元测试。我的问题是,是否:
storage = DictStorage()
value = 8
key = 'foo'
storage.store(key, value)
actual = storage.get(key)
assert actual == 8, "cache value for %s is %s, expected %s" % (key, str(actual), str(value))
是get方法的合适单元测试,或者是否有用于测试实现集合类型对象的类的Pythonic模式。
答案 0 :(得分:2)
我不知道是否有任何“特定于集合”,但测试结构对我来说很好。唯一的区别是我会使用unittest
包并将其定义为测试用例:
import unittest
class MyStorageInterface(object):
def store(self, key, value):
raise NotImplementedError("Class must be subclassed")
def get(self, key):
raise NotImplementedError("Class must be subclassed")
class DictStorage(MyStorageInterface):
def __init__(self):
self._cache = dict()
def store(self, key, value):
self._cache[key] = value
def get(self, key):
return self._cache[key]
class DictStorageTests(unittest.TestCase):
def setUp(self):
self._sut = DictStorage()
def test_storing_and_retrieving_value(self):
value_in = 8
key = 'foo'
self._sut.store(key, value_in)
value_out = self._sut.get(key)
self.assertEqual(value_in, value_out)
if __name__ == '__main__':
unittest.main()
<强>输出强>
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK