【问题标题】:How to test access to a private function?如何测试对私有函数的访问?
【发布时间】:2016-03-03 14:33:54
【问题描述】:

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

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

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

如果只有函数random_function() 并且我们有一个Serial 的对象,我们就不能像object.random_function() 这样访问函数。

但是,如果您考虑一个小组正在从事一个项目的情况,并且有一些方法显然应该是private...

在编写测试用例(在 C++ 中)时如何考虑这一点?

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

【问题讨论】:

  • 我不了解你,但如果我尝试使用私有函数,我会收到编译器错误。你不会遇到这种情况吗?
  • @BoBTFish OP:“不,我不想知道如何测试私有函数。” ——所以不,我认为这不是他们想要的。我认为他们想测试访问是否是私有的(例如,如果函数更改为具有public 访问权限,则希望测试失败)。
  • 您能否编辑您的问题以澄清一下?你让我们所有人都在猜测你想做什么
  • 为什么不能实例化该类的对象? Serial() 应该是构造函数(必须与类同名)还是我遗漏了什么?
  • 也许如果我们有一个可以编译的代码 sn-p 我们可以提供帮助?

标签: c++ unit-testing testing


【解决方案1】:

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;
}

【讨论】:

  • 有没有可能random_function也是一个模板参数?
  • 由于typeof,无法使用 Visual Studio 15 (MSVC14) 进行编译。将其更改为 decltype 有效。
【解决方案2】:

诀窍是使用SFINAE:编写一对函数,一个定义Random::random_function 是否为public,一个定义Random::random_function 是否为private

根据您的描述,第一个函数导致测试失败,第二个函数导致测试通过,但是在测试相反的情况时,您显然可以反转该逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-07
    • 2017-01-19
    • 2016-01-20
    • 2011-08-07
    • 2014-03-06
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    相关资源
    最近更新 更多