Faking Templates

Top  Previous  Next

Isolator++ Professional supports faking template classes. The syntax uses the a.Fake.Instance API, just like when faking concrete classes.

 

Consider a simple template class:

 

template <class K>

class MyTemplateClass {

   K a, b;

 

public:

   MyTemplateClass(K _aK _b) { a = _a; b = _b; }

   K getSum() { return a + b; }

};

 

To change the behavior of the getSum method, you can use the following test:

 

TEST_F(TemplatesTests, MyTemplateClass_getSum_Return7

{

   // Arrange

   auto a = Isolator();  

   auto fakeMyClass = a.Fake.Instance<MyTemplateClass<int>>();

   a.CallTo(fake->getSum()).WillReturn(7);

 

   // Act

   int num = fake->getSum();

 

   // Assert

   ASSERT_EQ(num, 7);

}

 

Faking multiple type templates works the same way:

 

template <class T1, class T2>

class MyTemplateClass {

   T1 t1;

   T2 t2;

 

public:

   MyTemplateClass(T1 _t1T2 _t2) { t1 = _t1t2 = _t2; }

   T1 getSum() { return t1 + static_cast<T1>t2; }

};

 

TEST_F(TemplatesTests, MyTemplateClass_getSum_Return7) 

{

   // Arrange

   auto a = Isolator();  

   auto fakeMyClass = a.Fake.Instance<MyTemplateClass<long,int>>();

   a.CallTo(fake->getSum()).WillReturn(7);

   

   // Act

   int num = fake->getSum();

 

   // Assert

   ASSERT_EQ(num, 7);

}

 

Note: linuxsymbol To fake multiple type templates on Linux you'll need to use a typedef.

 

typedef MyTemplateClass<long,int> MyTemplate_long_int; // Necessary only on Linux

 

auto fake = a.Fake.Instance<MyTemplate_long_int>();

 

 


Copyright  Typemock Ltd. 2009-2025.  All Rights Reserved.