加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

TD中的TDD.如何测试私有类的朋友功能?

发布时间:2020-12-14 04:48:53 所属栏目:百科 来源:网络整理
导读:如果我有一个带有帮助器(私有成员)类的类,就像这样 class Obj; class Helper { friend class Obj; private: int m_count; Helper(){ m_count = 0;}; // Note this is a private constructor void incrementCount(){ ++m_count; }; }; class Obj { Helper *m_
如果我有一个带有帮助器(私有成员)类的类,就像这样

class Obj;
    class Helper {
        friend class Obj;
        private:
        int m_count;
        Helper(){ m_count = 0;};  // Note this is a private constructor
        void incrementCount(){
            ++m_count;
        };
    };
    class Obj {
        Helper *m_pHelper;
        // note that this is a private getter
        int getHelperCount() { return m_pHelper->m_count; };

        // the public API starts here
        public:
        Obj() { m_pHelper = new Helper(); };
        void incrementCount(){ m_pHelper->incrementCount(); };
    };

那么我怎么可能TDD这样的系统呢?

auto obj = new Obj();
    obj->incrementCount();
    // what to assert???

这是我的问题,以下只是一些背景知识.

回答一些答案和评论.

If noone outside the class should be interested,then your tests should not be interested either. – Arne Mertz

If nobody is interested in the value outside the class,why are you – utnapistim

即使外面没有人需要该值,我仍然可能想知道如果它设置正确,因为它被使用该值的类的其他自包含内部方法使用.也许值是控制器用它来更新模型的速度.或者它可能是视图将用它在屏幕上绘制内容的位置.事实上,Obj的所有其他组件都能够访问该变量.这可能是一个糟糕的设计问题,在这种情况下,我想知道我可以有更好的替代方案.该设计列在本文底部的背景部分.

define private public – Marson Mao

喜欢这种巧妙滥用关键词哈哈.但可能还没有被认为是最好的解决方案.

You need to “expose” the friendship relation in the header of your class. Thus you have to acknowledge there the existence of a class used to test yours.
If you use the pImpl idiom,you could make the members of the pImpl itself all public,the pImpl itself private and give your unit tests access to the pImpl – CashCow

这是否意味着我应该在我原来的课堂上为考试做好准备?或者为它添加额外的“测试”方法?
我刚刚开始使用TDD.使用测试类依赖项来侵入原始类是否常见(或更好)?我不认为我有适当的知识来判断.有什么建议吗?

其他:AFAIK TDD不只是编写测试,而是开发过程.我已经读过,我应该只对公共接口编写测试.但问题是,与所讨论的情况一样,大多数代码都包含在私人类中.我如何使用TDD创建这些代码?

背景

仅供参考,如果您想知道我为什么要上私人课程:
我正在开发一个来自cocos2dx的游戏.游戏引擎采用节点树结构进行更新,渲染等,每个游戏对象都将继承引擎中提供的Node类.现在我想在游戏对象上实现MVC模式.因此,对于每个对象,我基本上创建了一个Object类,其中包含3个辅助类,这些类对应于名为ObjectModel,ObjectView,ObjectController的每个MVC组件.从理论上讲,没有人应该直接访问MVC类,只能通过Object类以某种方式访问??它,所以我将其中的3个私有化.将MVC组件明确地作为类的原因是因为视图和控制器以不同的速率更新(更具体地,控制器执行依赖于帧的更新,而视图基于模型数据执行简单的插值). Model类是纯粹出于宗教原因而创建的lol.

提前致谢.

解决方法

#define私有公共技巧可以通过某些编译器修改函数符号的方式产生副作用(Visual c编译器在其名称中包含访问说明符)

您还可以使用using语句更改可见性:

struct ObjTest : public Obj
{
   using Obj::incrementCount;
}

但就像其他人说的那样,尽量不要测试私人物品.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读