I want to create a unit test environment for our project. But I am lost about how to create mocks for members of the classes. I want to explain my question with an example.
In my older projects, we were using a mock selection mechanism which is very ugly in my opinion. Here is the elder method:
class member {
};
class member_mock_1 {
};
class member_mock_2 {
};
class parent {
#if defined UNIT_TEST_1
typedef member_t member_mock_1;
#elif defined UNIT_TEST_2
typedef member_t member_mock_2;
#else
typedef member_t member;
#endif
private:
member_t mem;
};
The first question is mocking the classes of the member object with typedefing in or out of the parent class is a proper way or not? What is the best practice? If I want to use a unit testing framework, like gtest, should I use this kind of way or is there another way to mocking members?
Note 1: If the virtual mechanism is activated, it is ok to create base classes to ease mocking, if a class is pod or something, I don't want to use this mechanism.
Note 2: I also find ugly passing the types of members as a template parameter, everything becomes template in the project. I don't want to do that. Here is an example:
template <typename M>
class parent {
private:
M mem;
};
#if defined UNIT_TEST_1
typedef parent_t parent<member_mock_1>;
#elif defined UNIT_TEST_2
typedef parent_t parent<member_mock_2>;
#else
typedef parent_t parent<member>;
#endif
Here is the method i am suggesting here:
member_mock_1.hpp
class member_mock_1 {
};
member_mock_2.hpp
class member_mock_2 {
};
mock.hpp
template <typename TYPE>
struct mock { using type = TYPE; };
#define ENABLE_MOCKING(NamE) \
using NamE ## _t = mock<NamE>::type
member_mock.hpp
#if define UNIT_TEST_1
template<>
struct mock<member> { using type = member_mock_1 };
#endif
#if define UNIT_TEST_2
template<>
struct mock<member> { using type = member_mock_2 };
#endif
member.hpp
class member {
};
ENABLE_MOCKING(member);
parent.hpp
class parent {
private:
member_t mem;
};
Method I have mentioned above works for normal classes. For template classes some extra works should be done, i think.
So as a conclusion, I am suggesting a structure for unit testing like above. May be it is unnecessary, there are some other mechanisms or ways to cover that requirement. Maybe I still reinventing the wheel :(
Please suggest a way you know for mocking members of a class.
Second question of mine is, I want to use gtest and gmock for our unit test. What do you suggest about that?
Third is there are some mechanisms accessing private members of the classes, like defining friend classes, writing public: instead of private: with preprocessor and etc. Which way do you suggest? May be it is totally unnecessary
Thanks.
Aucun commentaire:
Enregistrer un commentaire