Template accepts a type argument and an object of the same type by reference in constructor Template accepts a type argument. Makes a copy of the constructor argument or simply does not take one Template accepts a type argument and instantiates multiple interrelated templates without virtual functions

Template accepts a type argument and an object of the same type by reference in constructor

template <class T> class TemplateUnderTest { T *t_; public: TemplateUnderTest(T *t) : t_(t) {} void SomeMethod() { t->DoSomething(); t->DoSomeOtherThing(); } }; struct MockT { void DoSomething() { // Some assertions here. } void DoSomeOtherThing() { // Some more assertions here. } }; class UnitTest { void Test1() { MockT mock; TemplateUnderTest<MockT> test(&mock); test.SomeMethod(); assert(DoSomethingWasCalled(mock)); assert(DoSomeOtherThingWasCalled(mock)); } };

Template accepts a type argument. Makes a copy of the constructor argument or simply does not take one

friend

template <class T> class TemplateUnderTest { T t_; friend class UnitTest; public: void SomeMethod() { t.DoSomething(); t.DoSomeOtherThing(); } }; class UnitTest { void Test2() { TemplateUnderTest<MockT> test; test.SomeMethod(); assert(DoSomethingWasCalled(test.t_)); // access guts assert(DoSomeOtherThingWasCalled(test.t_)); // access guts } };

UnitTest::Test2

TemplateUnderTest

MockT

Template accepts a type argument and instantiates multiple interrelated templates without virtual functions

CallData

CallData

CallData

Request

Response

template <class Request, class Response> class CallData { grpc::ServerCompletionQueue *cq_; grpc::ServerContext context_; grpc::ServerAsyncResponseWriter<Response> responder_; // ... some more state public: using RequestType = Request; using ResponseType = Response; CallData(grpc::ServerCompletionQueue *q) : cq_(q), responder_(&context_) {} void HandleRequest(Request *req); // application-specific code Response *GetResponse(); // application-specific code };

CallData

HandleRequest

HandleResponse

CallData

Some types from grpc namespace are instantiated internally and not passed via the constructor. ServerAsyncResponseWriter and ServerContext , for example. grpc::ServerCompletionQueue is passed as an argument to the constructor but it has no virtual functions. Only virtual destructor. grpc::ServerContext is created internally and has no virtual functions

CallData

ServerCompletionQueue

ServerAsyncResponseWriter

virtual

grpc::ServerAsyncResponseWriter

final

virtual

Solution: Traits

CallDataTraits

template <class CallData> class CallDataTraits { using ServerCompletionQueue = grpc::ServerCompletionQueue; using ServerContext = grpc::ServerContext; using ServerAsyncResponseWriter = grpc::ServerAsyncResponseWrite<typename CallData::ResponseType>; };

CallData

/// Unit testable CallData template <class Request, class Response> class CallData { typename CallDataTraits<CallData>::ServerCompletionQueue *cq_; typename CallDataTraits<CallData>::ServerContext context_; typename CallDataTraits<CallData>::ServerAsyncResponseWriter responder_; // ... some more state public: using RequestType = Request; using ResponseType = Response; CallData(typename CallDataTraits ::ServerCompletionQueue *q) : cq_(q), responder_(&context_) {} void HandleRequest(Request *req); // application-specific code Response *GetResponse(); // application-specific code };

grpc

/// In unit test code struct TestRequest{}; struct TestResponse{}; struct MockServerCompletionQueue{}; struct MockServerContext{}; struct MockServerAsyncResponseWriter{}; /// We want to unit test this type. using CallDataUnderTest = CallData<TestRequest, TestResponse>; /// A specialization of CallDataTraits for unit testing purposes only. template <> class CallDataTraits<CallDataUnderTest> { using ServerCompletionQueue = MockServerCompletionQueue; using ServerContext = MockServerContext; using ServerAsyncResponseWriter = MockServerAsyncResponseWrite; }; MockServerCompletionQueue mock_queue; CallDataUnderTest cdut(&mock_queue); // Now injected with mock types.

CallData

final

Unit testing your template code comes up from time to time. (You test your templates, right?) Some templates are easy to test. No others. Sometimes it's not clear how to about injecting mock code into the template code that's under test. I've seen several reasons why code injection becomes challenging.Here I've outlined some examples below with roughly increasing code injection difficulty.Lets start with the easy ones.This one appears straight-forward because the unit test simply instantiates the template under test with a mock type. Some assertion might be tested in the mock class. And that's about it.Of course, testing with just a single type argument says nothing about rest of the infinite number of types that one could pass to the template. A fancy way to say the same thing is templates areso we might have to get little more clever for more scientific testing. More on that later.For example,In this case accessing the object inside the template might be inaccessible due to access privileges.classes could be used.Thecan simply reach into the guts ofand verify the assertions on the internal copy ofFor this case, I'll take a real-life example: Asynchronous Google RPC In C++ async gRPC, there's something called, which as the name suggests, stores the. Atemplate can handle multiple RPC of different types. So it's not uncommon to make it a template.A genericaccepts two type argumentsand. This is how it may look likeThe unit test fortemplate must verify the behavior ofand. These functions call a number of functions of the members. So making sure they are called in correctly is paramount to the correctness of. However, there's a catch.The question is how to testwithout using full-blown gRPC in the tests? How to mock? How to mock, which is itself a template? and on and on...Withoutfunctions, substituting custom behavior becomes challenging. Hardcoded types such asare impossible to mock because, well, they are hardcoded and not injected.It makes little sense to start passing them as constructor arguments. Even if do that, it may be meaningless because they may beclasses or simply have nofunctions.So, what gives?Instead of injecting custom behavior by inheriting from a common type (as done in Object-Oriented programming), INJECT THE TYPE ITSELF. We use traits for that. We specialize the traits differently depending upon whether it's production code or unit test code.Consider the followingThis is the primary template for the trait and used for "production" code. Let's use it in thetemplate.Given the above code, it's clear that production code is still using the types from thenamespace. However, we can easily replace the grpc types with mock types. Checkout below.Traits allowed us to choose the types injected independing upon the situation. This technique has zero performance overhead as no unnecessary virtual functions were created to inject functionality. The technique can be used withclasses as well.