كيفية السخرية من الأساليب المحببة باستخدام Google Mock؟
-
26-09-2019 - |
سؤال
أحاول السخرية من طريقة templated.
هنا هو الفصل الذي يحتوي على طريقة السخرية:
class myClass
{
public:
virtual ~myClass() {}
template<typename T>
void myMethod(T param);
}
كيف يمكنني السخرية من الطريقة myMethod باستخدام Google MoCk؟
المحلول
في الإصدار السابق من Google Mock ، يمكنك فقط السخرية من الوظائف الافتراضية ، راجع توثيق في صفحة المشروع.
يسمح للإصدارات الحديثة بالسخرية الطرق غير الذروة, باستخدام ما يسمونه حقن التبعية HI-Perf.
مثل congusbongus
تنص على:
تعتمد Google Mock على إضافة متغيرات الأعضاء إلى دعم طريقة السخرية ، وبما أنه لا يمكنك إنشاء متغيرات أعضاء القالب ، فمن المستحيل أن تسخر من وظائف القالب
يتمثل حل بديل ، من تأليف Michael Harrington في رابط Googlegroups من التعليقات ، في جعل أساليب القالب متخصصة التي ستستدعي وظيفة عادية يمكن الاستهزاء بها. إنها لا تحل الحالة العامة ولكنها ستعمل على الاختبار.
struct Foo
{
MOCK_METHOD1(GetValueString, void(std::string& value));
template <typename ValueType>
void GetValue(ValueType& value);
template <>
void GetValue(std::string& value) {
GetValueString(value);
}
};
نصائح أخرى
إليكم المنشور الأصلي مرة أخرى مع تعليقات للمساعدة في الفهم:
struct Foo
{
// Our own mocked method that the templated call will end up calling.
MOCK_METHOD3(GetNextValueStdString, void(const std::string& name, std::string& value, const unsigned int streamIndex));
// If we see any calls with these two parameter list types throw and error as its unexpected in the unit under test.
template< typename ValueType >
void GetNextValue( const std::string& name, ValueType& value, const unsigned int streamIndex )
{
throw "Unexpected call.";
}
template< typename ValueType >
void GetNextValue( const std::string& name, ValueType& value )
{
throw "Unexpected call.";
}
// These are the only two templated calls expected, notice the difference in the method parameter list. Anything outside
// of these two flavors is considerd an error.
template<>
void GetNextValue< std::string >( const std::string& name, std::string& value, const unsigned int streamIndex )
{
GetNextValueStdString( name, value, streamIndex );
}
template<>
void GetNextValue< std::string >( const std::string& name, std::string& value )
{
GetNextValue< std::string >( name, value, 0 );
}
};