unit-testing - 单元测试 C++ SetUp() 和 TearDown()

标签 unit-testing googlemock

我目前正在使用 google mock 学习单元测试virtual void SetUp()的常用用途是什么?和 virtual void TearDown()在谷歌模拟中?带有代码的示例场景会很好。

最佳答案

它可以在每个测试的开始和结束时分解您想要执行的代码,以避免重复。

例如 :

namespace {
  class FooTest : public ::testing::Test {

  protected:
    Foo * pFoo_;

    FooTest() {
    }

    virtual ~FooTest() {
    }

    virtual void SetUp() {
      pFoo_ = new Foo();
    }

    virtual void TearDown() {
      delete pFoo_;
    }

  };

  TEST_F(FooTest, CanDoBar) {
      // You can assume that the code in SetUp has been executed
      //         pFoo_->bar(...)
      // The code in TearDown will be run after the end of this test
  }

  TEST_F(FooTest, CanDoBaz) {
     // The code from SetUp will have been executed *again*
     // pFoo_->baz(...)
      // The code in TearDown will be run *again* after the end of this test

  }

} // Namespace

关于unit-testing - 单元测试 C++ SetUp() 和 TearDown(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26030700/

相关文章:

c++ - Google Mock 测试类的真实行为

java - 如何使用@ContextConfiguration在本地和内存中测试Web Spring应用程序?

unit-testing - Golang 单元测试用户输入

c++ - 谷歌模拟中的 TEST_F 给出错误

c++ - 使用 gmock 将值设置为 void** 参数的通用自定义操作

c++ - 如何返回 gmock 中的输入参数之一

python - pytest 结果是什么意思?

python - 使用 Docker 测试 Mongo

c# - 单元测试——我做的对吗?

c++ - 为什么我需要第二个参数?