Come prendere in giro i metodi su modelli utilizzando Google Mock?
-
26-09-2019 - |
Domanda
Sto cercando di prendere in giro un metodo basato su modelli.
Questa è la classe che contiene il metodo per deridere:
class myClass
{
public:
virtual ~myClass() {}
template<typename T>
void myMethod(T param);
}
Come faccio a deridere il metodo myMethod utilizzando Google Mock?
Soluzione
Nella versione precedente di Google Mock è possibile solo funzioni virtuali finte, vedere la documentazione nella pagina del progetto.
versioni più recenti permesso di finta metodi non-virtuali , utilizzando quello che chiamano hi-perf iniezione di dipendenza .
Per quanto afferma congusbongus
:
Google Mock si basa sull'aggiunta di variabili membro al metodo di sostegno beffardo, e dal momento che non è possibile creare variabili membro template, è impossibile funzioni template finte
Una soluzione, da Michael Harrington nelle GoogleGroups collegamento dai commenti, è quello di far specializzato i metodi di modello che chiameranno una funzione normale che può essere preso in giro. Non risolve il caso generale ma funzionerà per il test.
struct Foo
{
MOCK_METHOD1(GetValueString, void(std::string& value));
template <typename ValueType>
void GetValue(ValueType& value);
template <>
void GetValue(std::string& value) {
GetValueString(value);
}
};
Altri suggerimenti
Ecco il post originale di nuovo con i commenti per aiutare a comprendere:
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 );
}
};