代码之家  ›  专栏  ›  技术社区  ›  Fantastic Mr Fox

如何只在调试中运行Google死亡测试?

  •  1
  • Fantastic Mr Fox  · 技术社区  · 8 年前

    我们有一系列的死亡测试来检查特定的调试 asserts 火。例如,我们构造如下:

    LockManager::LockManager(size_t numManagedLocks) :
        _numManagedLocks(numManagedLocks)
    {
        assert(_numManagedLocks <= MAX_MANAGABLE_LOCKS &&
            "Attempting to manage more than the max possible locks.");
    

    我们对它的失败进行了测试:

    EXPECT_DEATH(LockManager sutLockManager(constants::MAX_NUMBER_LOCKS + 1), 
        "Attempting to manage more than the max possible locks.");
    

    由于assert只在debug中编译,所以当组件在release中构建时,这些测试将失败。最好的方法是避免这个包裹 EXPECT_DEATH A中的测试 DEBUG 检测宏:

    #ifndef NDEBUG
         // DEATH TESTS
    #endif
    

    或者是否有一种方法更适合于谷歌测试?

    2 回复  |  直到 8 年前
        1
  •  1
  •   Spock77    8 年前

    因为assert()宏使用预处理器逻辑,所以解决方案也应该在这个级别上——通过条件编译。 您可以使用GoogleTest特定的禁用\语法(请参见 Temporarily Disabling Tests )写一些像

    #ifdef _DEBUG
    #define DEBUG_TEST_ 
    #else
    #define DEBUG_TEST_ DISABLED_
    #endif 
    

    你最初的建议看起来也不错,不过我最好直接写下:

    #ifdef _DEBUG 
     ...
    
        2
  •  0
  •   Fantastic Mr Fox    8 年前

    我们生成了一个工作宏来代替完整的死亡测试或 ASSERT_DEATH 出现在其他测试中:

    #if defined _DEBUG
    
        #define DEBUG_ONLY_TEST_F(test_fixture, test_name) \
            TEST_F(test_fixture, test_name)
        #define DEBUG_ONLY_ASSERT_DEATH(statement, regex) \
            ASSERT_DEATH(statement, regex)
    
    #else
    
        #define DEBUG_ONLY_TEST_F(test_fixture, test_name) \
            TEST_F(test_fixture, DISABLED_ ## test_name)
        #define DEBUG_ONLY_ASSERT_DEATH(statement, regex) \
            std::cout << "WARNING: " << #statement << " test in " << __FUNCTION__ << " disabled becuase it uses assert and fails in release.\n";
    
    #endif
    

    当然,我们需要重写我们使用的任何其他测试类型(例如 TEST_P 或 EXPECT_DEATH 但这不应该是个大问题。