如何为返回void和void *的函数编写googletest测试用例?

时间:2014-01-06 09:57:27

标签: function void googletest

我正在尝试使用googletest测试返回void和void *的函数。我只是一个初学者,直到现在我才使用EXPECT来测试代码。

请告诉我如何为void和void *函数编写测试用例。

示例代码可以提供很多帮助。 :)

由于

1 个答案:

答案 0 :(得分:1)

以下是您的Add功能以及投掷Divide功能的示例:

#include <stdexcept>
#include "gtest/gtest.h"

int global_sum(0), global_quotient(0);

void Add(int a, int b) {
  global_sum = a + b;
}

void Divide(int numerator, int divisor) {
  if (divisor == 0)
    throw std::logic_error("Can't divide by 0.");
  global_quotient = numerator / divisor;
}

TEST(Calculator, Add) {
  EXPECT_EQ(0, global_sum);

  Add(1, 2);
  EXPECT_EQ(3, global_sum);

  Add(-1, 1);
  EXPECT_EQ(0, global_sum);
}

TEST(Calculator, Divide) {
  EXPECT_EQ(0, global_quotient);

  EXPECT_NO_THROW(Divide(2, 1));
  EXPECT_EQ(2, global_quotient);

  EXPECT_THROW(Divide(1, 0), std::logic_error);
  EXPECT_EQ(2, global_quotient);

  EXPECT_NO_THROW(Divide(1, 2));
  EXPECT_EQ(0, global_quotient);
}

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}