3.7.0-rc 3.6.0 (latest) 3.5.0 3.4.0 3.3.0 3.2.0 2.48.0-rc 2.47.1 2.46.0 2.45.0 2.44.0 2.43.0 2.42.0 2.41.0 2.40.0 2.39.0 2.38.0 2.37.0 2.36.0 2.35.0 2.34.0 2.33.0 2.32.0 2.31.0 2.30.0 2.29.0 2.28.0 2.27.0 2.26.0 2.25.1 2.24.0 2.23.0 2.22.1 2.21.0 2.20.0 2.19.0 2.18.0 2.17.0 2.16.0 2.15.1 2.14.0 2.13.0 2.12.0 2.11.0 In this document we describe how to write unit tests that mock [`google::cloud::spanner::Client`](https://docs.cloud.google.com/cpp/docs/reference/spanner/latest/classgoogle_1_1cloud_1_1spanner_1_1Client) using Google Mock. This document assumes the reader is familiar with the Google Test and Google Mock frameworks and with the Cloud Spanner C++ Client.

### Mocking a successful ExecuteQuery

First include the headers for the Cloud Spanner Client, the mocking class, and the Google Mock framework.

    #include "google/cloud/spanner/client.h"
    #include "google/cloud/spanner/mocks/mock_spanner_connection.h"
    #include "google/cloud/spanner/mocks/row.h"
    #include <google/protobuf/text_format.h>
    #include <gmock/gmock.h>

The example uses a number of aliases to save typing and improve readability:

    using ::testing::Return;
    namespace spanner = ::google::cloud::spanner;

Create a mocking object for [`google::cloud::spanner::Connection`](https://docs.cloud.google.com/cpp/docs/reference/spanner/latest/classgoogle_1_1cloud_1_1spanner_1_1Connection):

      auto conn = std::make_shared<google::cloud::spanner_mocks::MockConnection>();

We will setup this mock in a second, but first let's look at how it is used to create a [`google::cloud::spanner::Client`](https://docs.cloud.google.com/cpp/docs/reference/spanner/latest/classgoogle_1_1cloud_1_1spanner_1_1Client) object:

      spanner::Client client(conn);

Once the client is created you can make calls on the client as usual:

      auto rows = client.ExecuteQuery(
          spanner::SqlStatement("SELECT Id, Greeting FROM Greetings"));

And then verify the results meet your expectations:

      int count = 0;
      using RowType = std::tuple<std::int64_t, std::string>;
      for (auto const& row : spanner::StreamOf<RowType>(rows)) {
        ASSERT_TRUE(row);
        auto expected_id = ++count;
        EXPECT_EQ(expected_id, std::get<0>(*row));
        EXPECT_EQ("Hello World", std::get<1>(*row));
      }

All of this depends on creating a [`google::cloud::spanner::RowStream`](https://docs.cloud.google.com/cpp/docs/reference/spanner/latest/classgoogle_1_1cloud_1_1spanner_1_1RowStream) that simulates the stream of results you want. To do so, you need to mock a source that streams [`google::cloud::spanner::Row`](https://docs.cloud.google.com/cpp/docs/reference/spanner/latest/classgoogle_1_1cloud_1_1spanner_1_1Row)s:

      auto source =
          std::make_unique<google::cloud::spanner_mocks::MockResultSetSource>();

The source must define the names and types of the columns returned by the query:

      auto constexpr kText = R"pb(
        row_type: {
          fields: {
            name: "Id",
            type: { code: INT64 }
          }
          fields: {
            name: "Greeting",
            type: { code: STRING }
          }
        })pb";
      google::spanner::v1::ResultSetMetadata metadata;
      ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(kText, &metadata));
      EXPECT_CALL(*source, Metadata()).WillRepeatedly(Return(metadata));

And then setup the mock to return the results. Note that the results are returned one value at a time, even if a row contains multiple values.

      EXPECT_CALL(*source, NextRow())
          .WillOnce(Return(google::cloud::spanner_mocks::MakeRow(
              {{"Id", spanner::Value(1)},
               {"Greeting", spanner::Value("Hello World")}})))
          .WillOnce(Return(google::cloud::spanner_mocks::MakeRow(
              {{"Id", spanner::Value(2)},
               {"Greeting", spanner::Value("Hello World")}})))

Note that the last value in the stream is indicated by an std::optional without a value:

          .WillOnce(Return(spanner::Row()));

Once the `source` has been created and its behavior mocked, you mock the behavior for `ExecuteQuery`:

      EXPECT_CALL(*conn, ExecuteQuery)
          .WillOnce([&source](spanner::Connection::SqlParams const&)
                        -> spanner::RowStream {
            return spanner::RowStream(std::move(source));
          });

### Full Listing

Finally we present the full code for this example:


    #include "google/cloud/spanner/client.h"
    #include "google/cloud/spanner/mocks/mock_spanner_connection.h"
    #include "google/cloud/spanner/mocks/row.h"
    #include <google/protobuf/text_format.h>
    #include <gmock/gmock.h>

    namespace {

    using ::testing::Return;
    namespace spanner = ::google::cloud::spanner;

    TEST(MockSpannerClient, SuccessfulExecuteQuery) {
      // Create a mock object to stream the results of a ExecuteQuery.
      auto source =
          std::make_unique<google::cloud::spanner_mocks::MockResultSetSource>();

      // Setup the return type of the ExecuteQuery results:
      auto constexpr kText = R"pb(
        row_type: {
          fields: {
            name: "Id",
            type: { code: INT64 }
          }
          fields: {
            name: "Greeting",
            type: { code: STRING }
          }
        })pb";
      google::spanner::v1::ResultSetMetadata metadata;
      ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(kText, &metadata));
      EXPECT_CALL(*source, Metadata()).WillRepeatedly(Return(metadata));

      // Setup the mock source to return some values:
      EXPECT_CALL(*source, NextRow())
          .WillOnce(Return(google::cloud::spanner_mocks::MakeRow(
              {{"Id", spanner::Value(1)},
               {"Greeting", spanner::Value("Hello World")}})))
          .WillOnce(Return(google::cloud::spanner_mocks::MakeRow(
              {{"Id", spanner::Value(2)},
               {"Greeting", spanner::Value("Hello World")}})))
          .WillOnce(Return(spanner::Row()));

      // Create a mock for `spanner::Connection`:
      auto conn = std::make_shared<google::cloud::spanner_mocks::MockConnection>();

      // Setup the connection mock to return the results previously setup:
      EXPECT_CALL(*conn, ExecuteQuery)
          .WillOnce([&source](spanner::Connection::SqlParams const&)
                        -> spanner::RowStream {
            return spanner::RowStream(std::move(source));
          });

      // Create a client with the mocked connection:
      spanner::Client client(conn);

      // Make the request and verify the expected results:
      auto rows = client.ExecuteQuery(
          spanner::SqlStatement("SELECT Id, Greeting FROM Greetings"));

      int count = 0;
      using RowType = std::tuple<std::int64_t, std::string>;
      for (auto const& row : spanner::StreamOf<RowType>(rows)) {
        ASSERT_TRUE(row);
        auto expected_id = ++count;
        EXPECT_EQ(expected_id, std::get<0>(*row));
        EXPECT_EQ("Hello World", std::get<1>(*row));
      }
    }

    }  // namespace