我已经执行了 Replace Method with Method Object 描述的“Beck ”重构.
现在,我有一个带有“run()”方法的类和一组将计算分解为更小单元的成员函数。如何测试这些成员函数?
我的第一个想法是,我的单元测试基本上是“run()”方法的副本(具有不同的初始化),但在每次调用成员函数之间使用断言来检查计算状态。
(我正在使用 Python 和 unittest 模块。)
class Train:
def __init__(self, options, points):
self._options = options
self._points = points
# other initializations
def run(self):
self._setup_mappings_dict()
self._setup_train_and_estimation_sets()
if self._options.estimate_method == 'per_class':
self._setup_priors()
self._estimate_all_mappings()
self._save_mappings()
def _estimate_all_mappings():
# implementation, calls to methods in this class
#other method definitions
作为 run()
方法实现的一部分,在调用不同方法之前和之后,成员属性的状态应该是什么,我对此抱有明确的期望。我应该对这些“私有(private)”属性做出断言吗?我不知道如何对这些方法进行单元测试。
另一种选择是我真的不应该测试这些。
最佳答案
我会回答我自己的问题。经过一番阅读和思考,我相信我不应该对这些私有(private)方法进行单元测试。我应该只测试公共(public)接口(interface)。如果进行内部处理的私有(private)方法足够重要,可以独立测试并且不仅仅是当前实现的巧合,那么这也许是一个迹象,表明它们应该被重构到一个单独的类中。
关于python - 如何对方法对象中的方法进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2784519/