md_doc_unit_testing.html 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
  5. <meta http-equiv="X-UA-Compatible" content="IE=9"/>
  6. <meta name="generator" content="Doxygen 1.8.6"/>
  7. <title>GRPC Core: How to write unit tests for gRPC C client.</title>
  8. <link href="tabs.css" rel="stylesheet" type="text/css"/>
  9. <script type="text/javascript" src="jquery.js"></script>
  10. <script type="text/javascript" src="dynsections.js"></script>
  11. <link href="search/search.css" rel="stylesheet" type="text/css"/>
  12. <script type="text/javascript" src="search/search.js"></script>
  13. <script type="text/javascript">
  14. $(document).ready(function() { searchBox.OnSelectItem(0); });
  15. </script>
  16. <link href="doxygen.css" rel="stylesheet" type="text/css" />
  17. </head>
  18. <body>
  19. <div id="top"><!-- do not remove this div, it is closed by doxygen! -->
  20. <div id="titlearea">
  21. <table cellspacing="0" cellpadding="0">
  22. <tbody>
  23. <tr style="height: 56px;">
  24. <td style="padding-left: 0.5em;">
  25. <div id="projectname">GRPC Core
  26. &#160;<span id="projectnumber">4.0.0</span>
  27. </div>
  28. </td>
  29. </tr>
  30. </tbody>
  31. </table>
  32. </div>
  33. <!-- end header part -->
  34. <!-- Generated by Doxygen 1.8.6 -->
  35. <script type="text/javascript">
  36. var searchBox = new SearchBox("searchBox", "search",false,'Search');
  37. </script>
  38. <div id="navrow1" class="tabs">
  39. <ul class="tablist">
  40. <li><a href="index.html"><span>Main&#160;Page</span></a></li>
  41. <li class="current"><a href="pages.html"><span>Related&#160;Pages</span></a></li>
  42. <li><a href="modules.html"><span>Modules</span></a></li>
  43. <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li>
  44. <li><a href="files.html"><span>Files</span></a></li>
  45. <li>
  46. <div id="MSearchBox" class="MSearchBoxInactive">
  47. <span class="left">
  48. <img id="MSearchSelect" src="search/mag_sel.png"
  49. onmouseover="return searchBox.OnSearchSelectShow()"
  50. onmouseout="return searchBox.OnSearchSelectHide()"
  51. alt=""/>
  52. <input type="text" id="MSearchField" value="Search" accesskey="S"
  53. onfocus="searchBox.OnSearchFieldFocus(true)"
  54. onblur="searchBox.OnSearchFieldFocus(false)"
  55. onkeyup="searchBox.OnSearchFieldChange(event)"/>
  56. </span><span class="right">
  57. <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
  58. </span>
  59. </div>
  60. </li>
  61. </ul>
  62. </div>
  63. <!-- window showing the filter options -->
  64. <div id="MSearchSelectWindow"
  65. onmouseover="return searchBox.OnSearchSelectShow()"
  66. onmouseout="return searchBox.OnSearchSelectHide()"
  67. onkeydown="return searchBox.OnSearchSelectKey(event)">
  68. <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&#160;</span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark">&#160;</span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark">&#160;</span>Macros</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(9)"><span class="SelectionMark">&#160;</span>Groups</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(10)"><span class="SelectionMark">&#160;</span>Pages</a></div>
  69. <!-- iframe showing the search results (closed by default) -->
  70. <div id="MSearchResultsWindow">
  71. <iframe src="javascript:void(0)" frameborder="0"
  72. name="MSearchResults" id="MSearchResults">
  73. </iframe>
  74. </div>
  75. </div><!-- top -->
  76. <div class="header">
  77. <div class="headertitle">
  78. <div class="title">How to write unit tests for gRPC C client. </div> </div>
  79. </div><!--header-->
  80. <div class="contents">
  81. <div class="textblock"><p>tl;dr: <a href="https://github.com/grpc/grpc/blob/master/test/cpp/end2end/mock_test.cc">Example code</a>.</p>
  82. <p>To unit-test client-side logic via the synchronous API, gRPC provides a mocked Stub based on googletest(googlemock) that can be programmed upon and easily incorporated in the test code.</p>
  83. <p>For instance, consider an EchoService like this:</p>
  84. <p>```proto service EchoTestService { rpc Echo(EchoRequest) returns (EchoResponse); rpc BidiStream(stream EchoRequest) returns (stream EchoResponse); } ```</p>
  85. <p>The code generated would look something like this:</p>
  86. <p>```c class EchoTestService final { public: class StubInterface { virtual ::grpc::Status Echo(::grpc::ClientContext* context, const ::grpc::testing::EchoRequest&amp; request, ::grpc::testing::EchoResponse* response) = 0; … std::unique_ptr&lt; ::grpc::ClientReaderWriterInterface&lt; ::grpc::testing::EchoRequest, ::grpc::testing::EchoResponse&gt;&gt; BidiStream(::grpc::ClientContext* context) { return std::unique_ptr&lt; ::grpc::ClientReaderWriterInterface&lt; ::grpc::testing::EchoRequest, ::grpc::testing::EchoResponse&gt;&gt;(BidiStreamRaw(context)); } … private: virtual ::grpc::ClientReaderWriterInterface&lt; ::grpc::testing::EchoRequest, ::grpc::testing::EchoResponse&gt;* BidiStreamRaw(::grpc::ClientContext* context) = 0; … } // End StubInterface … } // End EchoTestService ```</p>
  87. <p>If we mock the StubInterface and set expectations on the pure-virtual methods we can test client-side logic without having to make any rpcs.</p>
  88. <p>A mock for this StubInterface will look like this:</p>
  89. <p>```c class MockEchoTestServiceStub : public EchoTestService::StubInterface { public: MOCK_METHOD3(Echo, ::grpc::Status(::grpc::ClientContext* context, const ::grpc::testing::EchoRequest&amp; request, ::grpc::testing::EchoResponse* response)); MOCK_METHOD1(BidiStreamRaw, ::grpc::ClientReaderWriterInterface&lt; ::grpc::testing::EchoRequest, ::grpc::testing::EchoResponse&gt;*(::grpc::ClientContext* context)); }; ```</p>
  90. <p><b>Generating mock code:</b></p>
  91. <p>Such a mock can be auto-generated by:</p>
  92. <ol type="1">
  93. <li>Setting flag(generate_mock_code=true) on grpc plugin for protoc, or</li>
  94. </ol>
  95. <ol type="1">
  96. <li>Setting an attribute(generate_mock) in your bazel rule.</li>
  97. </ol>
  98. <p>Protoc plugin flag:</p>
  99. <p>``<code>sh protoc -I . --grpc_out=generate_mock_code=true:. --plugin=protoc-gen-grpc=</code>which grpc_cpp_plugin<code>echo.proto </code>``</p>
  100. <p>Bazel rule:</p>
  101. <p>```py grpc_proto_library( name = "echo_proto", srcs = ["echo.proto"], generate_mock = True, ) ```</p>
  102. <p>By adding such a flag now a header file <code>echo_mock.grpc.pb.h</code> containing the mocked stub will also be generated.</p>
  103. <p>This header file can then be included in test files along with a gmock dependency.</p>
  104. <p><b>Writing tests with mocked Stub.</b></p>
  105. <p>Consider the following client a user might have:</p>
  106. <p>```c class FakeClient { public: explicit FakeClient(EchoTestService::StubInterface* stub) : stub_(stub) {}</p>
  107. <p>void DoEcho() { ClientContext context; EchoRequest request; EchoResponse response; request.set_message("hello world"); Status s = stub_-&gt;Echo(&amp;context, request, &amp;response); EXPECT_EQ(request.message(), response.message()); EXPECT_TRUE(s.ok()); }</p>
  108. <p>void DoBidiStream() { EchoRequest request; EchoResponse response; ClientContext context; grpc::string msg("hello");</p>
  109. <p>std::unique_ptr&lt;ClientReaderWriterInterface&lt;EchoRequest, EchoResponse&gt;&gt; stream = stub_-&gt;BidiStream(&amp;context);</p>
  110. <p>request.set_message(msg "0"); EXPECT_TRUE(stream-&gt;Write(request)); EXPECT_TRUE(stream-&gt;Read(&amp;response)); EXPECT_EQ(response.message(), request.message());</p>
  111. <p>request.set_message(msg "1"); EXPECT_TRUE(stream-&gt;Write(request)); EXPECT_TRUE(stream-&gt;Read(&amp;response)); EXPECT_EQ(response.message(), request.message());</p>
  112. <p>request.set_message(msg "2"); EXPECT_TRUE(stream-&gt;Write(request)); EXPECT_TRUE(stream-&gt;Read(&amp;response)); EXPECT_EQ(response.message(), request.message());</p>
  113. <p>stream-&gt;WritesDone(); EXPECT_FALSE(stream-&gt;Read(&amp;response));</p>
  114. <p>Status s = stream-&gt;Finish(); EXPECT_TRUE(s.ok()); }</p>
  115. <p>void ResetStub(EchoTestService::StubInterface* stub) { stub_ = stub; }</p>
  116. <p>private: EchoTestService::StubInterface* stub_; }; ```</p>
  117. <p>A test could initialize this FakeClient with a mocked stub having set expectations on it:</p>
  118. <p>Unary RPC:</p>
  119. <p>```c MockEchoTestServiceStub stub; EchoResponse resp; resp.set_message("hello world"); Expect_CALL(stub, Echo(_,_,_)).Times(Atleast(1)).WillOnce(DoAll(SetArgPointee&lt;2&gt;(resp), Return(Status::OK))); FakeClient client(stub); client.DoEcho(); ```</p>
  120. <p>Streaming RPC:</p>
  121. <p>```c ACTION_P(copy, msg) { arg0-&gt;set_message(msg-&gt;message()); }</p>
  122. <p>auto rw = new MockClientReaderWriter&lt;EchoRequest, EchoResponse&gt;(); EchoRequest msg; EXPECT_CALL(*rw, Write(_, _)).Times(3).WillRepeatedly(DoAll(SaveArg&lt;0&gt;(&amp;msg), Return(true))); EXPECT_CALL(*rw, Read(_)). WillOnce(DoAll(WithArg&lt;0&gt;(copy(&amp;msg)), Return(true))). WillOnce(DoAll(WithArg&lt;0&gt;(copy(&amp;msg)), Return(true))). WillOnce(DoAll(WithArg&lt;0&gt;(copy(&amp;msg)), Return(true))). WillOnce(Return(false));</p>
  123. <p>MockEchoTestServiceStub stub; EXPECT_CALL(stub, BidiStreamRaw(_)).Times(AtLeast(1)).WillOnce(Return(rw));</p>
  124. <p>FakeClient client(stub); client.DoBidiStream(); ``` </p>
  125. </div></div><!-- contents -->
  126. <!-- start footer part -->
  127. <hr class="footer"/><address class="footer"><small>
  128. Generated on Wed Jun 21 2017 14:13:07 for GRPC Core by &#160;<a href="http://www.doxygen.org/index.html">
  129. <img class="footer" src="doxygen.png" alt="doxygen"/>
  130. </a> 1.8.6
  131. </small></address>
  132. </body>
  133. </html>