I have a code like this one:
void ClassA::Function()
{
ClassB b;
if (b.doSomething())
{
// ...
}
}
And mock for classB:
class ClassBMock: public classB
{
MOCK_METHOD(doSomething, bool(void));
}
Is it possible to test this function, having ClassBMock created instead of ClassB, so I can use EXPECT_CALL and control what doSomething returns?
No, if you instantiate an object of type ClassB in the context of your to-be-tested function, the compiler (and linker) will make sure that you get an object of type ClassB ;)
What you can do to get an instance of your mock class instead, is e.g. by means of a builder, factory function or you simply pass a pointer to the object b as a parameter to Function(). This way you can inject a mock object, when the code is tested.
Luckily we are talking about C++, so there is one further possible way: Provide a different definition of class ClassB in case ClassA::Function() is compiled/linked in the test context.
I.e. you need to have a different "build-tree" when building the test. Here you can refer to the source file of the productive source-tree, that contains the to-be-tested method. But you can include a different header with the mock definition of ClassB instead of the productive one. In case ClassB is defined in some other library, you link a mock version of it.
All this is not specific for GMock.
What GMock can do for you is summarized nicely in this Cookbook. You can see in virtually any case the construction of the mock/fake object is done in the context of the test coding. It then needs to be "injected" in the to-be-tested code in some way as described above.
Related
I have a two classes let's say classA and classB. classA calls a method in classB which saves some value in a database using the DaoClass.
I have to test if the values are getting saved in database.
#Mocks
private DaoClass dao;
#Mocks
private ClassB B;
#InjectMocks
private ClassA A;
A.someMethod(someArgument);
verify(B).someOtherMethod(someOtherArgument);
verify(dao).save(theCorrectValue);
This fails saying there were zero interactions with this mock. Wanted but not invoked dao.save(). Whereas B.someOtherMethod() was invoked.
I am new to development and testing and my understanding was that I just have to mock call a method in my first class and then that call would proceed like a normal call and all the methods in all the other classes would be called normally. But it seems that it only calls a method in classB and then does not do anything in classB. For example, I debugged by creating breakpoints all over ClassB:
ClassB someOtherMethod{
SomeCode;
SomeCode;
dao.save();
someCode;
return Something; }
In debugger I can see it goes to ClassB someOtherMethod() but after that it skips all the code and goes to return statement. Am I missing something? Do I need to go through some documents?
You would have to either
stub the ClassB someOtherMethod. Note that if you don't specify the return value of any of the mocked dependencies (with when()) it will return the default value for the return type - null for objects, 0 for primitive numbers, false for boolean, etc. This is why you must be getting Null when someOtherMethod is called.
Use Spy instead of Mock. if you want to call external service and perform calling of real dependency, or simply say, you want to run the program as it is and just stub specific methods, then use spy.
If i need to test if a method within class under test has been called or not, can it be done without Mockito (or any mocking tool for that matter)?
Reason asking is that wherever i read about Mockito and similar tools, it says one should never mock CUT but its dependencies (that part is clear).
So, if thats the case then there are only 2 options left:
there is some other way of testing it without mocking
or
the fact the method was called should not be tested itself but some side effect or methods return value
For example (trivial and non-realworld), class MyClass can have 2 methods: A() and B(). A conditionay calls B based on some internal state.
After arranging state & acting by calling A() we want to assert that B() was called.
Either its not possible without mocking the whole CUT or 2 methods like this in a single class are always SRP violation smell and call for redesign where B() should actually be (mocked) dependency of MyClass CUT.
So, whats correct?
Usually I tend to not even use spies, instead I prefer to write my code in a way that for any class I write:
I test only non-private methods, since they're entry points into the class under test. So, in your example, if a() calls b(), maybe b() should be be private and, as a consequence, should not be tested. To generalize, a() is something that a class "can do" (a behavior), so I test the behavior, and not the method itself. If this behavior internally calls other things - well, its an internal matter of that class, if possible I don't make any assumptions on how does the class work internally, and always prefer "white-box" testing.
I only test "one" non-private method in a test.
All the methods should return something (best option) or at least call dependencies, or change internal state of the object under test. The list of dependencies is always clean-to-understand, I can't instantiate the object of CUT without supplying it a list of dependencies. For example, using constructor dependency injection is a good way of doing this. I mock only dependencies indeed, and never mock / spy CUT. Dependencies are never static but injected.
Now with these simple rules, the need to "test if a method within class under test has been called or not" basically can boil down to one of the following:
you're talking about private method. In this case - don't test it, test only public things.
The method is public - in this case you explicitly call it in unit test, so its irrelevant.
Now lets ask why do you want to test this if a method within CUT has been called or not?
If you want to make sure that it changed something. If this "something" is within the class - in other words, its internal state has changed, check in test that the change is indeed done in the state by calling another method that allows to query the state
If this "something" is a code that is managed by dependency, create a mock of this dependency and verify that it was called with the expected parameters.
Take a look at the Mockito Documentation (https://static.javadoc.io/org.mockito/mockito-core/3.0.0/org/mockito/Mockito.html#13)
When using a Spy you can 'replace' a method in the same class that is under test.
#ExtendWith(MockitoExtension.class)
public class Test {
class MyClass {
public void a() {
b();
}
public void b() {
}
}
#Test
public void test() {
MyClass testClass = new MyClass();
MyClass spy = Mockito.spy(testClass);
Mockito.doNothing().when(spy).b();
spy.a();
Mockito.verify(spy, Mockito.times(1)).b();
}
}
So whether that is something that should be done is a different question ;)
I think it highly depends on what method B() is actually doing and whether that is supposed be part of MyClass in the first place.
Either its not possible without mocking the whole CUT
In this case we do not mock the whole CUT only the method you do not want to be called.
Reason asking is that wherever i read about Mockito and similar tools, it says one should never mock CUT but its dependencies (that part is clear).
I believe this statement is not entirely accurate in correlation with spying.
The whole point of spying in my eyes is to use it on the class under test. Why would one want to spy on a dependecy that is not even supposed to be part of the test in the first place?
I am writing a GMOCK test cases for a class:
class A{ .. void Text() .. };
Now one of the member method of class A has an class B type object embedded into it and also refers to static member methods:
void A::Text()
{
B bobj;
B::SMethod();
bobj->BMethod();
......
}
In such a case how can I mock B and its methods?
Instead of testing A, you can test a class derived from it, let's call it TestableA. In A make Text() virtual and in override use mock of the B. Also, have a look at this question for more ideas of how to mock classes with static methods.
Nevertheless, the best solution would be to break existing tight dependency between A and B by introducing an interface (e.g. InterfaceB) and injecting it into Text(). SMethod() would become a (non-static) member of the interface. In production you'd be injecting ActualB where ActualB::SMethod() calls static B::SMethod(). In tests you'd use MockB::SMethod(), tailored by test needs.
I have an ABC with several derived classes. To create these derived classes I use the factory pattern:
.h file:
class derivedFactory
{
public:
base* createInstance();
};
.cpp file:
base* derivedFactory::createInstance()
{
return new derived();
}
Is there any advantage to this over just having a free function:
.h file:
base* derivedFactoryFunction();
.cpp file:
base* derivedFactoryFunction()
{
return new derived();
}
Also: I use the abstract factory pattern for dependency injection. I might use an inheritance hierarchy based on the ABC:
class objectCreator
{
public:
base* create() = 0;
};
Is there any advantage to using this over a function pointer:
boost::function<base* ()> factory_ptr;
Using boost::bind/lambda this seems to make my code more composable, and if I wish I can wrap a real factory object in it. I can see that there may be a slight performance decrease but this is much to worry about as it is only called during startup.
It depends on how flexible your factory needs to be. If the factory needs external information (like from a configuration file, program options, etc) to determine how to construct objects, than an object makes sense. If all you will ever need is in the arguments to factory, than a function is probably fine.
The only advantage I can see to having a pointer is for testing, where you can use a different factory function.
Do you ever want more than one factory for a type? If so, you need factory objects.
Having a interface with a single method or a pointer to method is equivalent.
But in the second case you'll get into trouble if you want another method to go along with ther first one...
And the interface is more readable than the method pointer in my opinion.
Then you chose.
I'd say the advantage of having the factory function as a static method within the class itself is that it is clear that it is part of the lifecycle of that class. Making it separate means other programmers who use your class would have to look somewhere else to find the factory method.
I'm sorry I'm unsure of exactly what you mean by passing around the function pointer to the factor method, but I generally wouldn't use a function pointer if you don't have to. Function pointers cannot be inlined as they cannot be resolved at compile time, which means they could possibly be slower. But besides that, it just seems bad design to use a function pointer if you can already be sure of which function you're going to call at compile time.
Here's my issue, I'd like to mock a class that creates a thread at initialization and closes it at destruction. There's no reason for my mock class to actually create and close threads. But, to mock a class, I have inherit from it. When I create a new instance of my mock class, the base classes constructor is called, creating the thread. When my mock object is destroyed, the base classes destructor is called, attempting to close the thread.
How does one mock an RAII class without having to deal with the actual resource?
You instead make an interface that describes the type, and have both the real class and the mock class inherit from that. So if you had:
class RAIIClass {
public:
RAIIClass(Foo* f);
~RAIIClass();
bool DoOperation();
private:
...
};
You would make an interface like:
class MockableInterface {
public:
MockableInterface(Foo* f);
virtual ~MockableInterface();
virtual bool DoOperation() = 0;
};
And go from there.
First of all, it is not necessarily an unreasonable thing that your classes might be well designed for their use, but poorly designed for testing. Not everything is easy to test.
Presumably you want to use another function or class which makes use of the class which you want to mock (otherwise the solution is trivial). Lets call the former "User" and the latter "Mocked". Here are some possibilities:
Change User to use an abstract version of Mocked (you get to choose what kind of abstraction to use: inheritance, callback, templates, etc....).
Compile a different version of Mocked for your testing code (for example, #def out the RAII code when you compile your tests).
Have Mocked accept a constructor flag to turn off its behavior. I personally would avoid doing this.
Just suck up the cost of allocating the resource.
Skip the test.
The last two may be your only recourse if you can not modify User or Mocked. If you can modify User and you believe that designing your code to be testable is important, then you should explore the first option before any of the others. Note that there can be a trade off between making your code generic/flexible and keeping it simple, both of which are admirable qualities.
The pimpl idiom might suit you as well. Create your Thread class, with a concrete implementation that it brings in underneath. If you put in the right #defines and #ifdefs your implementation can change when you enable unit testing, which means that you can switch between a real implementation and a mocked one depending on what you are trying to accomplish.
One technique I've used is to use some form of decorator. Your final code has a method which creates its instance on the stack and then calls the same method, but on a member which is a pointer to your base class. When that call returns, your method returns destroying the instance you created.
At test time, you swap in a mock which doesn't create any threads, but just forwards to the method you want to test.
class Base{
protected:
Base* decorated;
public:
virtual void method(void)=0;
};
class Final: public Base{
void method(void) { Thread athread; decorated->method(); } // I expect Final to do something with athread
};
class TestBase: public Base{
void method(void) { decorated->method(); }
};