我有一个返回抽象类对象的函数。
AbstractClass some_function(int argument);
我假设如果argument == 1
那么some_function
应该返回DerivedClassOne
的对象,如果argument == 2
则应该DerivedClassTwo
。{{1}}我想通过简单的单元测试来检查这些假设。
什么是最好的(简单,可读,可靠且独立于任何第三方库和工具)检查方式?
答案 0 :(得分:1)
在您的示例中,some_function()
按值返回AbstractClass
,这意味着返回的对象会被切片,并且本身只会是AbstractClass
。多态性仅适用于指针和引用。无论哪种方式,您都可以使用dynamic_cast
进行验证检查。
例如:
AbstractClass* some_function(int argument);
...
AbstractClass *obj;
obj = some_function(1);
if (dynamic_cast<DerivedClassOne*>(obj) != NULL)
// returned the correct type...
else
// returned the wrong type...
obj = some_function(2);
if (dynamic_cast<DerivedClassTwo*>(obj) != NULL)
// returned the correct type...
else
// returned the wrong type...
或者:
AbstractClass& some_function(int argument);
...
try {
dynamic_cast<DerivedClassOne&>(some_function(1));
// returned the correct type...
}
catch (const std::bad_cast&) {
// returned the wrong type...
}
try {
dynamic_cast<DerivedClassTwo&>(some_function(2));
// returned the correct type...
}
catch (const std::bad_cast&) {
// returned the wrong type...
}
答案 1 :(得分:0)
使用dynamic_cast
,如果对象不是预期的子类,则会产生NULL指针。来自维基百科:
int main()
{
Base* basePointer = new Derived();
Derived* derivedPointer = NULL;
// To find whether basePointer is pointing to Derived type of object
derivedPointer = dynamic_cast<Derived*>(basePointer);
if (derivedPointer != NULL)
{
std::cout << "basePointer is pointing to a Derived class object"; // Identified
}
else
{
std::cout << "basePointer is NOT pointing to a Derived class object";
}
// Requires virtual destructor
delete basePointer;
basePointer = NULL;
return 0;
}