grpc/cpp/md_doc_unit_testing.html

98 lines
13 KiB
HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>GRPC C++: How to write unit tests for gRPC C client.</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">GRPC C++
&#160;<span id="projectnumber">1.22.0</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">How to write unit tests for gRPC C client. </div> </div>
</div><!--header-->
<div class="contents">
<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>
<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>
<p>For instance, consider an EchoService like this:</p>
<div class="fragment"><div class="line">service EchoTestService {</div><div class="line"> rpc Echo(EchoRequest) returns (EchoResponse);</div><div class="line"> rpc BidiStream(stream EchoRequest) returns (stream EchoResponse);</div><div class="line">}</div></div><!-- fragment --><p>The code generated would look something like this:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>EchoTestService final {</div><div class="line"> <span class="keyword">public</span>:</div><div class="line"> <span class="keyword">class </span>StubInterface {</div><div class="line"> <a class="code" href="namespacegrpc_1_1protobuf_1_1util.html#a717f1a5db6c98d3f27340afd6f28bf7e">virtual ::grpc::Status</a> Echo(::<a class="code" href="classgrpc__impl_1_1_client_context.html">grpc::ClientContext</a>* context, const ::grpc::testing::EchoRequest&amp; request, ::grpc::testing::EchoResponse* response) = 0;</div><div class="line"></div><div class="line"> std::unique_ptr&lt; ::grpc::ClientReaderWriterInterface&lt; ::grpc::testing::EchoRequest, ::grpc::testing::EchoResponse&gt;&gt; BidiStream(::<a class="code" href="classgrpc__impl_1_1_client_context.html">grpc::ClientContext</a>* context) {</div><div class="line"> <span class="keywordflow">return</span> std::unique_ptr&lt; ::grpc::ClientReaderWriterInterface&lt; ::grpc::testing::EchoRequest, ::grpc::testing::EchoResponse&gt;&gt;(BidiStreamRaw(context));</div><div class="line"> }</div><div class="line"></div><div class="line"> <span class="keyword">private</span>:</div><div class="line"> virtual ::grpc::ClientReaderWriterInterface&lt; ::grpc::testing::EchoRequest, ::grpc::testing::EchoResponse&gt;* BidiStreamRaw(::<a class="code" href="classgrpc__impl_1_1_client_context.html">grpc::ClientContext</a>* context) = 0;</div><div class="line"></div><div class="line"> } <span class="comment">// End StubInterface</span></div><div class="line"></div><div class="line">} <span class="comment">// End EchoTestService</span></div></div><!-- fragment --><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>
<p>A mock for this StubInterface will look like this:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>MockEchoTestServiceStub : <span class="keyword">public</span> EchoTestService::StubInterface {</div><div class="line"> <span class="keyword">public</span>:</div><div class="line"> MOCK_METHOD3(Echo, ::<a class="code" href="classgrpc_1_1_status.html">grpc::Status</a>(::<a class="code" href="classgrpc__impl_1_1_client_context.html">grpc::ClientContext</a>* context, const ::grpc::testing::EchoRequest&amp; request, ::grpc::testing::EchoResponse* response));</div><div class="line"> MOCK_METHOD1(BidiStreamRaw, ::<a class="code" href="classgrpc_1_1_client_reader_writer_interface.html">grpc::ClientReaderWriterInterface&lt; ::grpc::testing::EchoRequest, ::grpc::testing::EchoResponse&gt;</a>*(::<a class="code" href="classgrpc__impl_1_1_client_context.html">grpc::ClientContext</a>* context));</div><div class="line">};</div></div><!-- fragment --><p><b>Generating mock code:</b></p>
<p>Such a mock can be auto-generated by:</p>
<ol type="1">
<li>Setting flag(generate_mock_code=true) on grpc plugin for protoc, or</li>
</ol>
<ol type="1">
<li>Setting an attribute(generate_mocks) in your bazel rule.</li>
</ol>
<p>Protoc plugin flag:</p>
<div class="fragment"><div class="line">protoc -I . --grpc_out=generate_mock_code=true:. --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` echo.proto</div></div><!-- fragment --><p>Bazel rule:</p>
<div class="fragment"><div class="line">grpc_proto_library(</div><div class="line"> name = <span class="stringliteral">&quot;echo_proto&quot;</span>,</div><div class="line"> srcs = [<span class="stringliteral">&quot;echo.proto&quot;</span>],</div><div class="line"> generate_mocks = <span class="keyword">True</span>,</div><div class="line">)</div></div><!-- fragment --><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>
<p>This header file can then be included in test files along with a gmock dependency.</p>
<p><b>Writing tests with mocked Stub.</b></p>
<p>Consider the following client a user might have:</p>
<div class="fragment"><div class="line"><span class="keyword">class </span>FakeClient {</div><div class="line"> <span class="keyword">public</span>:</div><div class="line"> <span class="keyword">explicit</span> FakeClient(EchoTestService::StubInterface* stub) : stub_(stub) {}</div><div class="line"></div><div class="line"> <span class="keywordtype">void</span> DoEcho() {</div><div class="line"> <a class="code" href="namespacegrpc.html#a35a61e2e00942ae1f40dda77413425ac">ClientContext</a> context;</div><div class="line"> EchoRequest request;</div><div class="line"> EchoResponse response;</div><div class="line"> request.set_message(<span class="stringliteral">&quot;hello world&quot;</span>);</div><div class="line"> <a class="code" href="namespacegrpc_1_1protobuf_1_1util.html#a717f1a5db6c98d3f27340afd6f28bf7e">Status</a> s = stub_-&gt;Echo(&amp;context, request, &amp;response);</div><div class="line"> EXPECT_EQ(request.message(), response.message());</div><div class="line"> EXPECT_TRUE(s.ok());</div><div class="line"> }</div><div class="line"></div><div class="line"> <span class="keywordtype">void</span> DoBidiStream() {</div><div class="line"> EchoRequest request;</div><div class="line"> EchoResponse response;</div><div class="line"> <a class="code" href="namespacegrpc.html#a35a61e2e00942ae1f40dda77413425ac">ClientContext</a> context;</div><div class="line"> <a class="code" href="namespacegrpc.html#ab04a87625da3bf85cdaf5e7856b00203">grpc::string</a> msg(<span class="stringliteral">&quot;hello&quot;</span>);</div><div class="line"></div><div class="line"> std::unique_ptr&lt;ClientReaderWriterInterface&lt;EchoRequest, EchoResponse&gt;&gt;</div><div class="line"> stream = stub_-&gt;BidiStream(&amp;context);</div><div class="line"></div><div class="line"> request.set_message(msg <span class="stringliteral">&quot;0&quot;</span>);</div><div class="line"> EXPECT_TRUE(stream-&gt;Write(request));</div><div class="line"> EXPECT_TRUE(stream-&gt;Read(&amp;response));</div><div class="line"> EXPECT_EQ(response.message(), request.message());</div><div class="line"></div><div class="line"> request.set_message(msg <span class="stringliteral">&quot;1&quot;</span>);</div><div class="line"> EXPECT_TRUE(stream-&gt;Write(request));</div><div class="line"> EXPECT_TRUE(stream-&gt;Read(&amp;response));</div><div class="line"> EXPECT_EQ(response.message(), request.message());</div><div class="line"></div><div class="line"> request.set_message(msg <span class="stringliteral">&quot;2&quot;</span>);</div><div class="line"> EXPECT_TRUE(stream-&gt;Write(request));</div><div class="line"> EXPECT_TRUE(stream-&gt;Read(&amp;response));</div><div class="line"> EXPECT_EQ(response.message(), request.message());</div><div class="line"></div><div class="line"> stream-&gt;WritesDone();</div><div class="line"> EXPECT_FALSE(stream-&gt;Read(&amp;response));</div><div class="line"></div><div class="line"> <a class="code" href="namespacegrpc_1_1protobuf_1_1util.html#a717f1a5db6c98d3f27340afd6f28bf7e">Status</a> s = stream-&gt;Finish();</div><div class="line"> EXPECT_TRUE(s.ok());</div><div class="line"> }</div><div class="line"></div><div class="line"> <span class="keywordtype">void</span> ResetStub(EchoTestService::StubInterface* stub) { stub_ = stub; }</div><div class="line"></div><div class="line"> <span class="keyword">private</span>:</div><div class="line"> EchoTestService::StubInterface* stub_;</div><div class="line">};</div></div><!-- fragment --><p>A test could initialize this FakeClient with a mocked stub having set expectations on it:</p>
<p>Unary RPC:</p>
<div class="fragment"><div class="line">MockEchoTestServiceStub stub;</div><div class="line">EchoResponse resp;</div><div class="line">resp.set_message(<span class="stringliteral">&quot;hello world&quot;</span>);</div><div class="line">Expect_CALL(stub, Echo(_,_,_)).Times(Atleast(1)).WillOnce(DoAll(SetArgPointee&lt;2&gt;(resp), Return(<a class="code" href="namespacegrpc.html#aff1730578c90160528f6a8d67ef5c43baf6f3078af147d683afc70e09695c7a65">Status::OK</a>)));</div><div class="line">FakeClient client(stub);</div><div class="line">client.DoEcho();</div></div><!-- fragment --><p>Streaming RPC:</p>
<div class="fragment"><div class="line">ACTION_P(copy, msg) {</div><div class="line"> arg0-&gt;set_message(msg-&gt;message());</div><div class="line">}</div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">auto</span> rw = <span class="keyword">new</span> MockClientReaderWriter&lt;EchoRequest, EchoResponse&gt;();</div><div class="line">EchoRequest msg;</div><div class="line">EXPECT_CALL(*rw, Write(_, _)).Times(3).WillRepeatedly(DoAll(SaveArg&lt;0&gt;(&amp;msg), Return(<span class="keyword">true</span>)));</div><div class="line">EXPECT_CALL(*rw, Read(_)).</div><div class="line"> WillOnce(DoAll(WithArg&lt;0&gt;(copy(&amp;msg)), Return(<span class="keyword">true</span>))).</div><div class="line"> WillOnce(DoAll(WithArg&lt;0&gt;(copy(&amp;msg)), Return(<span class="keyword">true</span>))).</div><div class="line"> WillOnce(DoAll(WithArg&lt;0&gt;(copy(&amp;msg)), Return(<span class="keyword">true</span>))).</div><div class="line"> WillOnce(Return(<span class="keyword">false</span>));</div><div class="line"></div><div class="line">MockEchoTestServiceStub stub;</div><div class="line">EXPECT_CALL(stub, BidiStreamRaw(_)).Times(AtLeast(1)).WillOnce(Return(rw));</div><div class="line"></div><div class="line">FakeClient client(stub);</div><div class="line">client.DoBidiStream();</div></div><!-- fragment --> </div></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Wed Jul 3 2019 14:51:27 for GRPC C++ by &#160;<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.13
</small></address>
</body>
</html>