I have a class looking somewhat like this:
class TheClassIWantToTest {
public:
TheClassIWantToTest(const IInput& input) {
setLocalParameter(input.getParameter());
}
// other stuff, e.g. setLocalParameter, defined below
}
where the input argument is defined as
class IInput {
virtual double getParameter() const = 0;
}
I also have an implementation of IInput which I use in my system, and a mock implementation created with Google Mocks.
Now, I want to be able to do something like
MockInput mock; // MockInput : IInput
TheClassIWantToTest sut(mock);
in my tests, while doing
RealInput theRealStuff; // RealInput : IInput
TheClassIWantToTest(theRealStuff);
but when I try to compile, I get errors about no method TheClassIWantToTest(MockInput) being defined. I tried to define a copy-constructor for IInput that takes a MockInput, but then I get error: definition of implicitly-declared IInput(const MockInput&) since I haven't defined the method in my class declaration.
However, I'd rather avoid declaring the copy constructor in the base class definition, since that would mean defining test methods in my production code. (I realize I could solve this by just taking a IInput* pointer instead, but if possible I'd like to avoid this too.)
I can't imagine I'm the first to try to accomplish this, but I haven't been able to find out how to do it. Is there a way? If so, how do you do it?
Try the dynamical cast:
RealInput theRealStuff; // RealInput : IInput
TheClassIWantToTest(dynamic_cast<const IInput&>(theRealStuff));
Related
I have to test the following classes with gmock and since I'm pretty new to Gmock Testing in general, I have no idea, where I'm getting these errors from. So I have my Model class in the Model.hpp, which looks like this:
class Model {
public:
Model(double delta_t) : Delta_t(delta_t){};
void add_submodel(std::unique_ptr< Submodel > submodel_ptr); //function adds submodels to private vector below
private:
std::vector<std::unique_ptr< Submodel>> submodel;
protected:
const double Delta_t;
};
The class Model above is using the class Submodel, which is defined like this:
class Submodel {
public:
virtual ~ Submodel() {};
virtual unsigned int get_number_of_states() = 0;
}
I have also defined the corresponding Mock Class for Submodel:
class MockSubmodel : public Submodel {
public:
MOCK_METHOD(unsigned int, get_number_of_states,(),(override));
};
So far so good. Now, I want to test, whether the function model.add_subproblem(std::unique_ptr submodel_ptr) actually adds Submodels to the Model. So therefore I started to define the following test:
TEST(modelTest, Add_Submodel) {
Model::Model model(1);
auto mock1_ptr = std::make_unique<Model::MockSubmodel>();
model.add_subproblem(mock1_ptr);
}
The error I'm getting here is:
error: no viable conversion from 'unique_ptr<Model::MockSubmodel>' to 'unique_ptr<Model::Submodel>'
So my question: What is the right way to pass MockSubmodel as a pointer into add_submodel(), such that it can be recognised as a Submodel? I thought this would happen automatically because of gmock structure?
The add_submodel function takes its std::unique_ptr<Submodel> parameter by value. When you call model.add_subproblem(mock1_ptr);, this would result in mock1_ptr being copied. However, unique_ptr is not copyable.
To fix this, you can remove the variable and directly pass the temporary, as in model.add_subproblem(std::make_unique<Model::MockSubmodel>());. Alternatively, you can move the unique_ptr in, as in model.add_subproblem(std::move(mock1_ptr)); (but you must remember that mock1_ptr will become nullptr after this point).
I am trying to mock an abstract class but I keep getting compiling errors from inside the GMock headers. I can't share the actual code, but is almost the same as bellow. The mocking was working fine, but I had to change the "DoStuff" function to take an object but reference. Since then it doesn't compile. The error is something like * GMock can't compare "Element" to long long *.
"C++ code"
using ::testing::NiceMock;
class Element{};
class Foo
{
public:
virtual void DoStuff(Element&) = 0;
};
class MockFoo : public Foo
{
public:
MockFoo() {};
MOCK_METHOD1(DoStuff, void(Element&));
};
TEST(example, test)
{
NiceMock<MockFoo> mf;
Element element{};
EXPECT_CALL(mf, DoStuff(element)).Times(1);
mf.DoStuff(element);
}
Look at generic comparisons matchers.
If you want to check exactly the same element is passed via mf.DoStuff to your mocked object - use ::testing::Ref matcher:
EXPECT_CALL(mf, DoStuff(Ref(element)));
(Note: that Times(1) is default - so not really necessary).
If you like to check if passed objects has exactly the same value - define comparison operator for it - or use some proper matcher - like ::testing::Property - like:
EXPECT_CALL(mf, DoStuff(AllOf(Property(&Example::getX, expectedXValue),
Property(&Example::getY, expectedYValue))));
I guess your exact problems are because your actual Example class is abstract and/or does not have operator == - so default matcher ::testing::Eq cannot be used.
I have classes like this:
class ParkingLot
{
public:
int spaces;
virtual bool something() { return true; }
}
class ParkingLotBuilding
{
public:
ParkingLot Floor1, Floor2;
}
I've got a whole lot of functions that take ParkingLotBuilding. Let's say someone (me) derives from ParkingLot and ParkingLotBuilding:
class DerivedParkingLot : public ParkingLot
{
public:
virtual bool something() { return false; }
}
class DerivedParkingLotBuilding : public ParkingLotBuilding
{
public:
// how can I make it so that Floor1 and Floor2 are for DerivedParkingLot?
}
I've got functions I don't control that are like this:
CheckBuilding( ParkingLotBuilding &building )
{
if(building.Floor1.something() == true)
// error
}
If I pass a DerivedParkingLotBuilding object to that function how do I make it so that it calls DerivedParkingLot::something() to return false? Is that possible? Sorry if I didn't explain this right I'm not sure how to ask about the problem. Thanks
As JohnSmith pointed out, you can't override data members, just member functions. Since ParkingLotBuilding contains ParkingLot values, and not ParkingLot pointers or references, they can't be used polymorphically, even in DerivedParkingLot. (That's just how C++ works: only pointers and references can have a dynamic type.)
That means that if you can't change the ParkingLotBuilding class (or the CheckBuilding function), then you're stuck. There is no deriving you can do that will get the CheckBuilding function to operate on a DerivedParkingLot object.
The moral of this story is that classes must be designed for inheritance from the beginning.
In fact you just to call the DerivedParkingLot function from a ParkingLot instance ?
Your code already did it by specifiying the something method as virtual, it will automaticaly search for the lowest method in his inherited tree.
A simple way to test it is to implement the something method in ParkingLot and DerivedParkingLot, put different message in each and check it
One way you might be able to approach this is by making ParkingLot a template class.
template<typename T>
class ParkingLotBuilding
{
public:
T Floor1, Floor2;
}
Then when creating a ParkingLotBuilding, you could use these types:
ParkingLotBuilding<ParkingLot>
ParkingLotBuilding<DerivedParkingLot>
Also if you don't like templating all the time and want to just use ParkingLotBuilding and DerivedParkingLotBuilding, you could rename the class to something like Building and use typedefs:
typedef Building<ParkingLot> ParkingLotBuilding
typedef Building<DerivedParkingLot> DerivedParkingLotBuilding
This approach isn't exactly inheritance between the ParkingLotBuilding types (and may not be the best approach - I've never seen this before), but it might do what you need.
In your example, Floor1 has no way of knowing whether it was instantiated inside of ParkingLotBuilding or DerivedParkingLotBuilding.
You could use RTTI to deal with this something like:
CheckBuilding (ParkingLotBuilding *building)
{
if (dynamic_cast<DerivedParkingLogBuilding*>(building))
{
// Floor is in a derived parking log building
}
else
{
// Floor is in a parking lot building
}
}
Not exactly the best was of doing this though, as pointed out above.
I am working on a small project in C++ that requires me to create an object of a custom class I wrote in another one of my classes. The class is called FIRFilterModule, It has a simple blank constructor.
Being of a java background, my impulse is to create it like this:
class SensorInput{
public:
FIRFilterModule firFilter;
...More Class Members...
SensorInput():firFilter(FIRFilterModule()){}
...};
However this compiles with the ever so helpful error message of "Error within this context". I'm a little lost why that doesn't work. Increasing my confusion I changed the code to this:
class SensorInput{
public:
FIRFilterModule firFilter;
...More Class Members...
SensorInput(){}
...};
It works.
Can someone help me understand why this is so?
In this particular case, running of the default constructor for a member field, you don't have to do anything. The constructor is run automatically. So you can just write
class SensorInput{
public:
FIRFilterModule firFilter;
SensorInput() { ... }
};
The member initialization list is only needed when you need to call a constructor which has arguments or initialize POD types. For example say the FIRFilterModule had a constructor which took an int. Then you would use the memeber initialization list
SensorInput() : firFilter(42) { ... }
The code you posted is correct.
Maybe you forgot to include the header where FIRFilterModule is declared.
Otherwise, everything should work.
I have a simple, low-level container class that is used by a more high-level file class. Basically, the file class uses the container to store modifications locally before saving a final version to an actual file. Some of the methods, therefore, carry directly over from the container class to the file class. (For example, Resize().)
I've just been defining the methods in the file class to call their container class variants. For example:
void FileClass::Foo()
{
ContainerMember.Foo();
}
This is, however, growing to be a nuisance. Is there a better way to do this?
Here's a simplified example:
class MyContainer
{
// ...
public:
void Foo()
{
// This function directly handles the object's
// member variables.
}
}
class MyClass
{
MyContainer Member;
public:
void Foo()
{
Member.Foo();
// This seems to be pointless re-implementation, and it's
// inconvenient to keep MyContainer's methods and MyClass's
// wrappers for those methods synchronized.
}
}
Well, why not just inherit privatly from MyContainer and expose those functions that you want to just forward with a using declaration? That is called "Implementing MyClass in terms of MyContainer.
class MyContainer
{
public:
void Foo()
{
// This function directly handles the object's
// member variables.
}
void Bar(){
// ...
}
}
class MyClass : private MyContainer
{
public:
using MyContainer::Foo;
// would hide MyContainer::Bar
void Bar(){
// ...
MyContainer::Bar();
// ...
}
}
Now the "outside" will be able to directly call Foo, while Bar is only accessible inside of MyClass. If you now make a function with the same name, it hides the base function and you can wrap base functions like that. Of course, you now need to fully qualify the call to the base function, or you'll go into an endless recursion.
Additionally, if you want to allow (non-polymorphical) subclassing of MyClass, than this is one of the rare places, were protected inheritence is actually useful:
class MyClass : protected MyContainer{
// all stays the same, subclasses are also allowed to call the MyContainer functions
};
Non-polymorphical if your MyClass has no virtual destructor.
Yes, maintaining a proxy class like this is very annoying. Your IDE might have some tools to make it a little easier. Or you might be able to download an IDE add-on.
But it isn't usually very difficult unless you need to support dozens of functions and overrides and templates.
I usually write them like:
void Foo() { return Member.Foo(); }
int Bar(int x) { return Member.Bar(x); }
It's nice and symmetrical. C++ lets you return void values in void functions because that makes templates work better. But you can use the same thing to make other code prettier.
That's delegation inheritance and I don't know that C++ offers any mechanism to help with that.
Consider what makes sense in your case - composition (has a) or inheritance (is a) relationship between MyClass and MyContainer.
If you don't want to have code like this anymore, you are pretty much restricted to implementation inheritance (MyContainer as a base/abstract base class). However you have to make sure this actually makes sense in your application, and you are not inheriting purely for the implementation (inheritance for implementation is bad).
If in doubt, what you have is probably fine.
EDIT: I'm more used to thinking in Java/C# and overlooked the fact that C++ has the greater inheritance flexibility Xeo utilizes in his answer. That just feels like nice solution in this case.
This feature that you need to write large amounts of code is actually necessary feature. C++ is verbose language, and if you try to avoid writing code with c++, your design will never be very good.
But the real problem with this question is that the class has no behaviour. It's just a wrapper which does nothing. Every class needs to do something other than just pass data around.
The key thing is that every class has correct interface. This requirement makes it necessary to write forwarding functions. The main purpose of each member function is to distribute the work required to all data members. If you only have one data member, and you've not decided yet what the class is supposed to do, then all you have is forwarding functions. Once you add more member objects and decide what the class is supposed to do, then your forwarding functions will change to something more reasonable.
One thing which will help with this is to keep your classes small. If the interface is small, each proxy class will only have small interface and the interface will not change very often.