本文介绍了当assert()意外触发时,如何抑制Google测试中的终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

讨论了如何捕获失败的断言,例如你设置你的灯具,使assert()失败,你看到不错的输出。但我需要的是相反的。我想测试assert()成功。但如果它失败,我想有好的输出。

Here it's discussed how to catch failing assert, e.g. you setup your fixture so that assert() fails and you see nice output. But what I need is the opposite. I want to test that assert() succeeds. But in case it fails I want to have nice output. At that point it just terminates when it snags on assert().

#define LIMIT 5

struct Obj {
    int getIndex(int index) {
        assert(index < LIMIT);
        // do stuff;
    }
}

Obj obj;

TEST(Fails_whenOutOfRange) {
    ASSERT_DEATH(obj->getIndex(6), "");
}

TEST(Succeeds_whenInRange) {
    obj->getIndex(4);
}

上面是一个假设的例子。我想要第二个测试不会终止,万一它失败,例如如果我设置LIMIT为3.毕竟,ASSERT_DEATH在assert()失败时会以某种方式终止。

Above is contrived example. I want second test not to terminate in case it fails, for example if I set LIMIT to 3. After all, ASSERT_DEATH suppresses somehow termination when assert() fails.

推荐答案

以下只是我的意见,但对我来说似乎你要么测试错误的东西,工具

The following is just my opinion, but it seems for me that you are either testing a wrong thing, or using a wrong tool.

Assert(C assert())不用于验证输入,它用于捕获不可能的情况。例如,它将从发布代码中消失,因此您不能依赖它。

Assert (C assert()) is not for verifying input, it is for catching impossible situations. It will disappear from release code, for example, so you can't rely on it.

您应该测试的是您的函数实现。您应该决定,您对无效输入值的规范是什么:

What you should test is your function specification rather than implementation. And you should decide, what is your specification for invalid input values:


  • 未定义的行为,因此 assert

  • Undefined behavior, so assert is fine, but you can't test it with unit-test, because undefined behavior is, well, undefined.

定义的行为。那么你应该是一致的,不管 NDEBUG 在场。在我看来,抛出异常是正确的事情,而不是调用 std :: abort ,这几乎是无用的用户(不能被拦截和正确处理)。

Defined behavior. Then you should be consistent regardless of NDEBUG presence. And throwing exception, in my opinion, is the right thing to do here, instead of calling std::abort, which is almost useless for user (can't be intercepted and processed properly).

这篇关于当assert()意外触发时,如何抑制Google测试中的终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 19:49