0

I am trying to use the GTest framework for My project. I created one sample code to test using Test Fixture.

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <iostream>

using testing::NiceMock;
using testing::Return;
enum class ValidationErrors : std::uint8_t
{
  kSuccess,
  kFailure,
};
class Validation
{
 public:
  Validation(int Alg)
  {}
  virtual ValidationErrors Initialize()
  {
    std::cout << __FUNCTION__ << std::endl;
    return ValidationErrors::kSuccess;
  }
  virtual ~Validation() = default;
};
class ValidationMock : public Validation
{
 public:
  ValidationMock() : Validation(1)
  {}
  MOCK_METHOD0(Initialize, ValidationErrors());
};

class Send
{
 public:
  Send()
  {}
  Send(int id, std::unique_ptr<Validation> validator) : validator_(std::move(validator))
  {
    std::cout << __FUNCTION__ << std::endl;
  }
  void Start(const std::uint32_t& size)
  {
    std::cout << __FUNCTION__ << std::endl;
    validator_->Initialize();
  }
  std::unique_ptr<Validation> validator_;
};

using NiceValidationMock = NiceMock<ValidationMock>;
class SendTextFixture : public testing::Test
{
 public:
  SendTextFixture() : validator_(std::make_unique<NiceValidationMock>())
  {
    sendClass_ = Send(5, std::move(validator_));
  }
  std::unique_ptr<NiceValidationMock> validator_;
  Send sendClass_;
};
TEST_F(SendTextFixture, DemoTest)
{
  sendClass_.Start(1);
  EXPECT_CALL(*validator_, Initialize()).WillOnce(Return(ValidationErrors::kSuccess));
  EXPECT_TRUE(true);
}

I have Start class which having the dependency on Validation class. So I created a Mock class for Validation.In Test Fixture I am trying to pass as ValidationMock object to Start class. In ValidationMock class I created one mock for Initialize method.

In the TestCase, I am trying to invoke Initialize method using EXPECT_CALL after that I am getting the below error.

1: [27630.783955]~DLT~  764~INFO     ~FIFO /tmp/dlt cannot be opened. Retrying later...
1: Running main() from gtest_main.cc
1: [==========] Running 1 test from 1 test case.
1: [----------] Global test environment set-up.
1: [----------] 1 test from SendTextFixture
1: [ RUN      ] SendTextFixture.DemoTest
1: Send
1: Start
1/1 Test #1: testpackage ......***Failed    0.32 sec

0% tests passed, 1 tests failed out of 1

Total Test time (real) =   0.32 sec

I am not able to understand what is the exact problem. Are there any mistakes in the above Test Fixture approach?

Quarra
  • 2,527
  • 1
  • 19
  • 27
goodman
  • 424
  • 8
  • 24
  • 2
    You are trying to call `EXPECT_CALL` on a `nullptr`. `validator_` is `nullptr` because you move it into `Send` object. – Yksisarvinen Oct 23 '20 at 15:30
  • @Yksisarvinen Thanks, man. I did that mistake. – goodman Oct 23 '20 at 16:29
  • I was having same kind of issues, please take a look at this question https://stackoverflow.com/questions/40508033/dependency-injection-with-unique-ptr-to-mock – Quarra Oct 26 '20 at 08:13

0 Answers0