C++ How can I mock an asio::awaitable method

Viewed 35

I want to mock the following line from boost asio library.

auto bytes = co_await socket.async_read(boost::asio::buffer(data), boost::asio::use_awaitable);

I thought of creating an interface which will represent the socket, then implement that interface for production by using asio and for testing by implementing a mock class of my own.

class MockSocket{
  asio::awaitable<size_t> async_read(boost::asio::buffer&& buffer){
    this.buffer = buffer;
    co_await this.something;
    co_return this.size;
  }

  void complete_read(string dataToPutInBuffer){
     this.buffer.write(dataToPutInBuffer);
     this.size = dataToPutInBuffer.length();
     this.something.resume();
  }
}

I have no idea what this.something should be. the asio::awaitable doesn't seem to have a resume() method.

1 Answers

You can use async_result or async_initiate to implement your own initiation function that takes an Asio CompletionToken.

Note also that Beast contains a stream that models AsyncStream - which is enough to satisfy e.g. asio::async_read* family of operations.

See it here: test::stream

Related