c++ - 如何测试对私有(private)函数的访问?

标签 c++ unit-testing testing

我想知道如何测试对私有(private)函数的访问。示例:

class Random{
    public:
        ...
    private:
        Serial();
        OR
        random_function();

在这种情况下,不可能实例化随机类的对象,因为 Serial是私有(private)的。

如果只有函数random_function()我们有一个对象 Serial我们无法访问 object.random_function() 之类的功能.

但是如果你考虑这样一个情况,一个小组正在做一个项目,并且有一些方法显然应该是 private ...

在编写测试用例(在 C++ 中)时怎么可能考虑到这一点?

编辑: 我正在寻找的是一个测试场景,我可以在其中测试访问: 如果函数更改为具有公共(public)访问权限,则测试失败。

最佳答案

来自 here 的回答

#include <iostream>

class Random1
{
public:
    int random_function() { return 0; }
};

class Random2
{
private:
    int random_function() { return 0; }
};

// SFINAE test
template <typename T>
class has_random_function
{
    typedef char one;
    typedef long two;

    template <typename C> static one test( typeof(&C::random_function) ) ;
    template <typename C> static two test(...);    

public:
    enum { value = sizeof(test<T>(0)) == sizeof(char) };
};

int main(int argc, char *argv[])
{
    std::cout << "Random1: " << has_random_function<Random1>::value << std::endl;
    std::cout << "Random2: " << has_random_function<Random2>::value << std::endl;
    return 0;
}

关于c++ - 如何测试对私有(private)函数的访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35775029/

相关文章:

c++ - Qt QLabel HTML 字体大小严重失败

c++ - 链接/编译使用 boost/filesystem.hpp 的程序

c++ - 使用临时地址安全吗?

.net - 如何找到 NetTcpBinding (WCF) 可用的 TCP 端口(以便服务器可以绑定(bind)到它)

javascript - 期望变量为 null 或 bool 值

c++ - 在每个系统日志 C++ 之前调用 openlog

python - 如何模拟数据库的方法

android - 单元测试定位服务

testing - stub 常规类的所有方法?

iphone - 如何在将最终分发版本提交给 iPhone 应用商店进行审核之前对其进行测试?