如何对方法对象中的方法进行单元测试? [英] How do I unit test the methods in a method object?

查看:38
本文介绍了如何对方法对象中的方法进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经执行了用方法对象替换方法" 重构由 贝克.

I've performed the "Replace Method with Method Object" refactoring described by Beck.

现在,我有一个带有run()"方法的类和一堆将计算分解成更小的单元的成员函数.我如何测试这些成员函数?

Now, I have a class with a "run()" method and a bunch of member functions that decompose the computation into smaller units. How do I test those member functions?

我的第一个想法是,我的单元测试基本上是run()"方法的副本(具有不同的初始化),但在每次调用成员函数之间使用断言来检查计算状态.

My first idea is that my unit tests be basically copies of the "run()" method (with different initializations), but with assertions between each call to the member functions to check the state of the computation.

(我使用 Python 和 unittest 模块.)

(I'm using Python and the unittest module.)

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() 方法实现的一部分在调用不同方法之前和之后成员属性的状态应该是什么我肯定有期望.我应该对这些私人"属性做出断言吗?我不知道如何对这些方法进行单元测试.

I definitely have expectations about what the the states of the member attributes should be before and after calls to the the different methods as part of the implementation of the run() method. Should I be making assertions about these "private" attributes? I don't know how else to unittest these methods.

另一个选择是我真的不应该测试这些.

The other option is that I really shouldn't be testing these.

推荐答案

我会回答我自己的问题.经过一些阅读和思考,我相信我不应该对这些私有方法进行单元测试.我应该只测试公共接口.如果执行内部处理的私有方法重要到足以独立测试,而不仅仅是当前实现的巧合,那么这可能表明它们应该被重构为一个单独的类.

I'll answer my own question. After a bit of reading and thinking, I believe I shouldn't be unit testing these private methods. I should just test the public interface. If the private methods that do the internal processing are important enough to test independently and are not just coincidences of the current implementation, then perhaps this is a sign that they should be refactored out into a separate class.

这篇关于如何对方法对象中的方法进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆