Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a googletest testcase for functions returning void and void *?

I'm trying to test functions returning void and void* using googletest. I'm just a beginner and I have just used EXPECT till now to test the code.

Please let me know how to write test cases for void and void * functions.

A sample code would help a lot. :)

Thanks

like image 621
user3094287 Avatar asked Oct 02 '22 23:10

user3094287


1 Answers

Here's an example with your Add function, and also with a throwing Divide function:

#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();
}
like image 139
Fraser Avatar answered Oct 13 '22 00:10

Fraser