How can I test a class with multiple template parameters?

1,844 views
Skip to first unread message

JamesLee

unread,
Jan 3, 2013, 3:06:18 AM1/3/13
to googletes...@googlegroups.com
I have a class CHouse:

template<typename A, typename B>
class CHouse
{
    ....
};

I want to test the protected methods of CHouse with gtest, so I write a fixture like this:

template<typename A, typename B>
class CHouseFixture : public CHouse<A, B>, public ::testing::Test
{
    ....
};

However, the TEST_F(CHouseFixture, MyTest) doesn't work. It can not be compiled.

How can I test the protected methods of a class with multiple template parameters?

Greg Miller

unread,
Jan 3, 2013, 9:52:40 AM1/3/13
to JamesLee, Google C++ Testing Framework
Consider creating a subclass of CHouse that redeclares the protected methods as public.

template <typename A, typename B>
class CHouse {
 protected:
  int DoWork() {
    return 42;
  }
};

template <typename A, typename B>
class CHouseForTesting : public CHouse<A, B> {
 public:
  using CHouse<A, B>::DoWork;
};

TEST(CHouse, Works) {
  CHouseForTesting<int, char> chouse;
  EXPECT_EQ(42, chouse.DoWork());
}

You can optionally also use a test fixture class (which is a subclass of ::testing::Test), but that's not required.

HTH,
Greg

JamesLee

unread,
Jan 3, 2013, 9:01:18 PM1/3/13
to googletes...@googlegroups.com, JamesLee
Hi Greg,

Thanks for your reply. It works for me.

However, I am new to unit test and I am curious about how to use a fixture class (a subclass of ::testing::Test) to test my CHouse class.

Would you please tell me that?

Thanks in advance.

Greg Miller於 2013年1月3日星期四UTC+8下午10時52分40秒寫道:

Greg Miller

unread,
Jan 3, 2013, 9:52:27 PM1/3/13
to JamesLee, Google C++ Testing Framework
On Thu, Jan 3, 2013 at 9:01 PM, JamesLee <cohere...@gmail.com> wrote:
Hi Greg,

Thanks for your reply. It works for me.

However, I am new to unit test and I am curious about how to use a fixture class (a subclass of ::testing::Test) to test my CHouse class.

Would you please tell me that?

Maybe something like this:

template <typename A, typename B>
class CHouse {
 protected:
  int DoWork() {
    return 42;
  }
};

template <typename A, typename B>
class CHouseForTesting : public CHouse<A, B> {
 public:
  using CHouse<A, B>::DoWork;
};

class CHouseFixture : public ::testing::Test {
 protected:
  CHouseForTesting<int char> chouse_;
};

TEST_F(CHouseFixture, Works) {
  EXPECT_EQ(42, chouse_.DoWork());
}
 
HTH,
Greg

JamesLee

unread,
Jan 7, 2013, 12:25:18 AM1/7/13
to googletes...@googlegroups.com, JamesLee
Thanks a lot. It works.

Greg Miller於 2013年1月4日星期五UTC+8上午10時52分27秒寫道:
Reply all
Reply to author
Forward
0 new messages