example_ut.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #include <library/cpp/testing/gmock_in_unittest/gmock.h>
  2. #include <library/cpp/testing/unittest/registar.h>
  3. #include <util/generic/string.h>
  4. // Set this variable to true if you want to see failures
  5. /////////////////////////////////////////////////////////
  6. static const bool fail = false;
  7. /////////////////////////////////////////////////////////
  8. class ITestIface {
  9. public:
  10. virtual ~ITestIface() {
  11. }
  12. virtual void Func1() = 0;
  13. virtual int Func2(const TString&) const = 0;
  14. };
  15. class TTestMock: public ITestIface {
  16. public:
  17. MOCK_METHOD(void, Func1, (), (override));
  18. MOCK_METHOD(int, Func2, (const TString&), (const, override));
  19. };
  20. using namespace testing;
  21. Y_UNIT_TEST_SUITE(TExampleGMockTest) {
  22. Y_UNIT_TEST(TSimpleTest) {
  23. TTestMock mock;
  24. EXPECT_CALL(mock, Func1())
  25. .Times(AtLeast(1));
  26. if (!fail) {
  27. mock.Func1();
  28. }
  29. }
  30. Y_UNIT_TEST(TNonExpectedCallTest) {
  31. TTestMock mock;
  32. EXPECT_CALL(mock, Func1())
  33. .Times(AtMost(1));
  34. mock.Func1();
  35. if (fail) {
  36. mock.Func1();
  37. }
  38. }
  39. Y_UNIT_TEST(TReturnValuesTest) {
  40. TTestMock mock;
  41. EXPECT_CALL(mock, Func2(TString("1")))
  42. .WillOnce(Return(1))
  43. .WillRepeatedly(Return(42));
  44. EXPECT_CALL(mock, Func2(TString("hello")))
  45. .WillOnce(Return(-1));
  46. UNIT_ASSERT_VALUES_EQUAL(mock.Func2("hello"), -1);
  47. UNIT_ASSERT_VALUES_EQUAL(mock.Func2("1"), 1);
  48. UNIT_ASSERT_VALUES_EQUAL(mock.Func2("1"), 42);
  49. UNIT_ASSERT_VALUES_EQUAL(mock.Func2("1"), 42);
  50. UNIT_ASSERT_VALUES_EQUAL(mock.Func2("1"), 42);
  51. UNIT_ASSERT_VALUES_EQUAL(mock.Func2("1"), 42);
  52. if (fail) {
  53. UNIT_ASSERT_VALUES_EQUAL(mock.Func2("hello"), -1); // expected to return -1 only once
  54. }
  55. }
  56. Y_UNIT_TEST(TStrictCallSequenceTest) {
  57. TTestMock mock;
  58. {
  59. InSequence seq;
  60. EXPECT_CALL(mock, Func1())
  61. .Times(1);
  62. EXPECT_CALL(mock, Func2(_))
  63. .Times(2)
  64. .WillOnce(Return(1))
  65. .WillOnce(Return(2));
  66. EXPECT_CALL(mock, Func1());
  67. }
  68. mock.Func1();
  69. UNIT_ASSERT_VALUES_EQUAL(mock.Func2("sample"), 1);
  70. if (fail) {
  71. mock.Func1();
  72. }
  73. UNIT_ASSERT_VALUES_EQUAL(mock.Func2(""), 2);
  74. if (!fail) {
  75. mock.Func1();
  76. }
  77. }
  78. Y_UNIT_TEST(TUninterestingMethodIsFailureTest) {
  79. StrictMock<TTestMock> mock;
  80. EXPECT_CALL(mock, Func1())
  81. .Times(1);
  82. mock.Func1();
  83. if (fail) {
  84. mock.Func1();
  85. }
  86. }
  87. }