我想知道如何测试对私有(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/