Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 谷歌测试:期待不同的类型?_C++_Testing_Googletest_Throw - Fatal编程技术网

C++ 谷歌测试:期待不同的类型?

C++ 谷歌测试:期待不同的类型?,c++,testing,googletest,throw,C++,Testing,Googletest,Throw,我正试着测试一下,如下图所示 #include <gtest/gtest.h> int Foo(int a, int b){ if (a == 0 || b == 0){ throw "don't do that"; } int c = a % b; if (c == 0) return b; return Foo(b, c); } TEST(FooTest, Throw2){ EXPECT_THROW(

我正试着测试一下,如下图所示

#include <gtest/gtest.h>
int Foo(int a, int b){
    if (a == 0 || b == 0){
        throw "don't do that";
    }
    int c = a % b;
    if (c == 0)
        return b;
    return Foo(b, c);
}
TEST(FooTest, Throw2){
    EXPECT_THROW(Foo(0,0), char*);
}
int main(int argc, char* argv[]){
    testing::InitGoogleTest(&argc,argv);
    return RUN_ALL_TESTS();
}
那么这里抛出的是什么类型呢?

“不要这样做”
是一个字符串文本,其类型是
const char[14]
。因此,它只能衰减为
const char*
,而不是像您期望的那样衰减为
char*

因此,将测试修改为
EXPECT_THROW(Foo(0,0),const char*)应该可以通过

顺便说一句,我不会在这种情况下抛出一个例外。IMO最好只返回
std::optional
(如果C++17不可用,则返回
boost::optional
)。得到错误的输入并不是我认为足够特殊的事情,不能保证出现异常


如果我必须抛出一个异常,那么抛出一个标准异常类型要比字符串文本更好。在这种情况下,
std::domain\u error
似乎是合适的。

注释不用于扩展讨论;这段对话已经结束。
Expected: Foo(0,0) throws an exception of type char*.
Actual: it throws a different type.