Tro*_*yvs 3 c++ testing googletest throw
我正在尝试测试 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();
}
Run Code Online (Sandbox Code Playgroud)
我预计“Throw2”应该成功。但它给出了这个错误信息:
Expected: Foo(0,0) throws an exception of type char*.
Actual: it throws a different type.
Run Code Online (Sandbox Code Playgroud)
那么这里抛出的类型是什么?
"don't do that"
是一个字符串文字,其类型为const char[14]
. 因此,它只能衰减到 a const char*
,而不是char*
像您期望的那样。
因此修改你的测试EXPECT_THROW(Foo(0,0), const char*);
应该可以通过。
顺便说一句,在这种情况下我不会抛出异常。IMO 最好简单地返回std::optional
(或者boost::optional
如果 C++17 不可用)。我认为获得错误的输入并不足以保证例外。
如果我必须抛出异常,那么抛出标准异常类型比字符串文字加载得更好。在这种情况下std::domain_error
似乎是合适的。