SaveArg for saving arrays - suggestions on how to make it work?

374 views
Skip to first unread message

Alex Shaver

unread,
Dec 19, 2014, 12:24:22 PM12/19/14
to googl...@googlegroups.com
Suppose I have a class Alpha that has a member Beta. (specifically, a pointer to Beta is injected at construction); Beta is some object that will be mocked out later. But we care about what, precisely, Alpha calls when it calls a function from beta.

class Gamma{
private:
   
char array[15];
public:
   
char* getArray() { return &array[0]; }
}

class Alpha{
private:
   
Beta* m_beta;
public:
    Alpha(Beta* external) : m_beta(external) {}

   
DoStuff(const Gamma& thing){
       
// ... maybe do some stuff with Gamma;
        Beta->Function(thing.getArray(), 15);
    }
};

class Beta{
public:
   
void Function(const char* array, int sizeOfArray);
};

class MockBeta : public Beta{
    MOCK_METHOD2
(Function, void(const char*, int));
}

using ::testing::_;

Test(AlphaTest, DoStuffTest){
   
char expectedArray[15] = {/*whatever*/};
   
char actualArray[15];
//    char* arrayPtr = nullptr;

   
MockBeta mock_external;
   
Alpha testObject(&mock_external);

    EXPECT_CALL
(mock_external, Function(_,_))
      .WillOnce(SaveArg<0>(&(&actualArray[0]));
//      .WillOnce(SaveArg<0>(&arrayPtr));
}


This example complains on compile: cannot take the address of an rvalue of type 'char *' (on the line:  .WillOnce(SaveArg<0>(&(&actualArray[0])); )

I've tried a variety of approaches.
  • A custom Action with parameter:  ACTION_P(SaveToPtr, ptr) { ptr = arg0; } doesn't work because ptr is a const value for the custom actions. 
  • Instead of an array, I could try with just a general char*. But then it gives a compiler error that it's incomatible with type 'const char *const'
And probably other stuff. 

Any ideas?

Alex Shaver

unread,
Dec 19, 2014, 12:45:10 PM12/19/14
to googl...@googlegroups.com
I think I figured out my problem to some degree (rubber ducking it, if you will).

Alpha calls Function(const Gamma& thing). Since thing is a const ref, I can't actually alter it in DoStuff.

Had Alpha not made a const call, the problem remains to a degree... except if you also assume that Gamma is Unit tested sufficiently to have a known/predictable outcome for the function getArray(); ie, whatever you may do to alter it is tested out elsewhere. Not always a true assumption, or wise one, but one that could be reasonably expected in such a framework.
Reply all
Reply to author
Forward
0 new messages