gpt4 book ai didi

c++ - 检查返回的对象是否属于 C++ 单元测试中的预期子类

转载 作者:行者123 更新时间:2023-11-28 02:31:05 26 4
gpt4 key购买 nike

我有一个返回抽象类对象的函数。

AbstractClass some_function(int argument);

我有一个假设,如果 argument == 1 那么 some_function 应该返回 DerivedClassOne 的对象,如果 argument == 2 它应该是 DerivedClassTwo。我想用一个简单的单元测试来检验这些假设。

最好的(简单、可读、可靠且独立于任何第三方库和工具)检查方式是什么?

最佳答案

在您的示例中,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...
}

关于c++ - 检查返回的对象是否属于 C++ 单元测试中的预期子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28975477/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com