代码之家  ›  专栏  ›  技术社区  ›  Troskyvs

GoogleTest:期待不同的类型?

  •  1
  • Troskyvs  · 技术社区  · 6 年前

    我试着测试一下你的投球,如下所示。

    #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();
    }
    

    我希望“Throw2”会成功。但它给出了错误信息:

    Expected: Foo(0,0) throws an exception of type char*.
    Actual: it throws a different type.
    

    那么这里抛出的是什么类型?

    1 回复  |  直到 6 年前
        1
  •  2
  •   StoryTeller - Unslander Monica    6 年前

    "don't do that" 是字符串文本,其类型为 const char[14] . 因此,它只能衰变为 const char* ,不是 char*

    EXPECT_THROW(Foo(0,0), const char*); 应该可以通过。

    std::optional (或 boost::optional 如果C++ 17不可用。得到不好的输入并不是一件我认为足够例外的事情。

    如果我必须抛出一个异常,那么抛出一个标准的异常类型比一个字符串更好。在这种情况下 std::domain_error