I am working with google mock to mock out the behavior of a class. The object I am mocking is a std:shared_prt. Somehow I can't redirect the method-call (of a mock method) to another method within the class.
The method I want to call redirectToStartOfBaseClass(), invokes the start()-Method of the base class (NMEADataControler)
The Mock Class:
class NMEADataControler_Mock : public NMEADataControler{
...
// The method I want to redirecto to ...
void redirectToStartOfBaseClass();
...
// ... when this mock method is called
MOCK_METHOD0(start, void());
...
}
The class with the test-fixture I am using
class TestFixtureClass : public ::testing::Test{
...
std::shared_ptr<NMEADataControler_Mock> NEMADummy;
...
}
Test Method:
TEST_F(TestFixtureClass, StupidTest){
...
ON_CALL(*NMEADummy, start())
.WillByDefault(Invoke( ?????? ) //What parameters to I have to put in here?
//To redirect to *NMEADummy->redirectToStartOfBaseClass()
}
I am not that experienced with C++ and quite new to it, so please forgive me if my mistakes are obvious and super stupid.
P.s: I searched for a solution for quite some time now and i can't find anything. That why I am asking you guys, I am quite desperate, I hope you can help me :(
If I'm understanding your question correctly, you just need to pass the NMEADataControler_Mock instance to Invoke, like this:
ON_CALL(*NMEADummy, start())
.WillByDefault(Invoke( NMEADummy.get(), &NMEADataControler_Mock::redirectToStartOfBaseClass));
Here, NMEADummy.get() returns a naked pointer to your dummy.
As an aside: I don't know your use case, so maybe a shared_ptr is a good call in your specific instance, but it doesn't seem like it. I advise you to use shared_ptr only in cases where you need multiple owners of a single resource. If the Fixture is going to be the only owner of your mock, I advise you to use a unique_ptr. shared_ptr are more complex to reason about, they can introduce hard to track ref count loops (they are not garbage collected, there is no mark and sweep happening) and are more heavy-weight, because of additional storage allocated for a control block. They are also slower, because of the atomic operations used to control their refcounts.
Related
Suppose we have a class like this :-
class A {
internal val obj : Obj
get() = Application.getbean(Obj::class)
fun method1(){
val result = obj.somefunc()
..../code/
}
fun method2(){
...../code/
}
}
I wan't to write unit test using the junit mockito framework to test the functionality of method1 and wan't to mock obj object . In some other threads on stackoverflow people has suggested to use constructor dependency injected but that is not possible in my case because of the issue of circular dependency . In some other answers people has suggested to move this object instantiation inside the method ,but i don't want to go that way .Is there any way to mock this obj object.
It's very hard to unit test code, that is written in a non-testable way. That is why you should inject dependencies and not to hold them, that is why you should obtain objects and not to create them by yourself. If you're assume that your code might be tested, always think how first.
In your case it's a bit difficult to mock Obj, but not impossible since the actual creation (constructor calling) of the object is done with a different class (not the one being tested).
In your example you're using static method, maybe you can mock it's behavior with a PowerMockito? Please take a look at this answer.
Other than that, I just can suggest to change the code.
To inject object creating class as a dependency or use some other approaches, which might involve some architectural changes.
I have a class with a public method that adds elements to a private vector and records the time when each element was added. Another public method in that class checks every element in the vector and removes ones that are older than 4 hours.
Those are the only public methods in the class (and there are no public members).
How can I use gtest to check that the remove function works?
I don't want the test to take 4 hours and I don't want to modify the source at all. Is this even possible?
UPDATE
GMock can override the method being used to get the current time. In many cases that will be a solution. However, GMock does not work for free functions (e.g. std::time). In that case, the GMock documentation only suggests wrapping the function in a class.
GMock will be useful, however, it's disappointing to find that it doesn't work for free functions and therefore the many cases where an STL free function or a function from a C-library needs to be mocked. The GMock documentation seems pretty clear about this but if someone happens to know a way around this (or another mocking framework without this limitation) let me know.
You need to make your class testable, there is no other way. Even for the most basic meaningful test, you will need to expose several things.
First of all, you will need to control the timestamp attached to your elements. To do so, you will need to inject an object into a constructor of your class that will return the current time, something alongside:
class YourClass {
// ...
shared_ptr<Timer> timer;
public:
YourClass(shared_ptr<Timer> t) : timer(t) {}
void addElement(Element e) {
e.timeAdded(timer->now());
container.push_back(e);
}
// ...
};
In this way you can pass in a fake timer in tests, which will set whichever time you want. In this way you won't have to wait at all.
Then, you need to expose some interface to inspect the result. For example, make your function that removes old elements return how many it removed. This would be the easiest way.
If you are unwilling to make these or similar changes, then there is nothing you can do to test your code in any meaningful fashion.
I recently implemented some code similar to below and submitted a pull request to get it added to our shared repository. The request was rejected and I was told this pattern was bad. Instead I should be putting my dependencies closer to the creation of my objects. If the parent object creates a child object then a Func childFactory should be passed in rather than a more generic object since that could be misused, increases coupling and becomes much harder to test.
public interface ILogResolverService
{
ILogger<T> Resolve<T>();
}
public class LogResolverService : ILogResolverService
{
private readonly IContainer _container;
public LogResolverService(IContainer container)
{
_container = container;
}
public ILogger<T> Resolve<T>()
{
return _container.Resolve<ILogger<T>>();
}
}
The idea of the code is to pass an object that can create an ILogger so that you can log with the correct class name. If you create a child view model for example you would let it create it's own ILogger etc
Since this issue has polarized opinions amoungst my colleagues I wanted to get an opinion from the community.
Added After Comments
I should have added that I don't see this as a ServiceLocator pattern because it is a strongly typed interface passed into the constructor of a parent. So you know all your dependencies up front. The worse that can happen is a new method is added to the interface ILogResolverService. Unless I'm missing something.
For what I can tell with the design you've outlined above, the main issue here is with your service being somewhat container aware.
Even if the return values you're proving are strongly typed and unambiguous the tricky part is somewhere else. The domain knowledge is too broad and overlap the container job.
It's always a good practice to explicitly provide the dependency your builder is using via an Add method.
public AddLoggerService[...]
Depending of your context you can ask the container to decorate/compile such service by adding all the needed dependency runtime.
Hope i have shed some light on the matter,
Regards.
When we have a classes like
class IntoController(IViewModelCreator viewModelCreator) {}
and
class ProductController(ICommandFactory commandFactory, IViewModelCreator viewModelCreator) {}
and
class ProductController(ICommandFactory commandFactory, IViewModelCreator viewModelCreator, IRepository repository) {}
and a lot of more. It takes a lot of time to mock this interfaces each time. What do you think about general purpose class which contains a big set of mocks?
class BaseControllerUnitTests
{
protected Mock<IViewModelCreator> ViewModelCreator { get;set; }
protected Mock<ICommandFactory> ViewModelCreator { get;set; }
protected Mock<IRepository> ViewModelCreator { get;set; }
}
Thanks in advance.
I actually do this; I just keep them in a different class called TestDataFactory so I don't get into problems with inheritance (just in case I have to extend some other base class in a test).
The factory shouldn't be global/static (see below).
Pro:
There is a single place for all tests to go to get a valid object graph
If the object graph changes, there is just one place to go to fix all the tests
You can keep references to the mocks in the factory for mocking inner method calls (i.e. you can ask for a ProductController and later, when you ask for an ICommandFactory, you get the one which was injected into the controller).
Con:
The test factory will become quite big. Eventually, you'll have to split it into several files.
Not all tests need the exact same mockup. Sometimes, you'll need to insert a real object. My solution is to allow to override the references which the factory keeps. But it makes the code even more clumsy.
In addition to Aaron Digulla's answer I'd like to suggest my colleague's post with some examples. He calls it Test Context. I use this approach pretty much as well.
The fact that's you're writing test code shouldn't mean that all software engineering best practices should go out the window.
If you have a subset of common functionality between your tests (in this case - mocking some methods of the tested class) then yes, by all means - you can extract a base class.
So I've decided to investigate using seams in PHPUnit, but I came across a problem
I rearranged my class in a way that I broke the dependencies to database class
db_Class::getMyData($vars);
became
self::getMyData($vars);
and I added functions to my code
protected static function getMyData($vars) {
return db_Class::getMyData($vars);
}
This was done so I can make a class that inherits this class and overloads the getMyData function. To be able to alter it when I run my test cases.
So for example in the seam class that extends the class above and overloads that function:
protected static function getMyData($vars) {
return array('id'=>1, 'name'=>"My Name");
}
This would be very useful, as I can alter the data as I like. However when using PHPUnit you have the possibility to run mocks using $this->getMock and similar. Would I ever be able to achieve this inside the seam class.
I'm trying to look for a solution where I am not using a dependency injector, which would be my other alternative, not so bad at all, just want to evaluate both alternatives.
Michael C. Feathers expressed a seam to be the following:
A seam is a place where you can alter behavior in your program without editing in that place.
So I might not get the full picture, and I've been trying to get it for a while now, and I just cant get my head around it. Please comment if you have any ideas or questions.
What I ask for is a way to work with mocks easy in different scenarios. I dont always want to return the same value in the seam, sometimes I want to return null to get an error, and sometimes an array with correct data, and sometimes something else probably.
Thanks
Because you must reference the class directly when calling static methods, you cannot override them as you can non-static methods. Static methods make testing difficult. I won't bother repeating what's written there, and I highly recommend following the links in the answers.
In any case, why is that method static? Being protected, you can call it only from the same class or its subclasses. Can you post more of the context here? How do you intend to use it, and where will you test it? Can you change it to non-static?
I found an answer to my question here:
http://sebastian-bergmann.de/archives/885-Stubbing-Hard-Coded-Dependencies.html
The idea here is that you can prepare testable version of X where only thing overriden will be getMyData:
protected static function getMyData($vars) {
return $some_dummy_data;
}
You write tests for X indirectly trough TestX.
Now lets assume that you change something in original X that breaks it. TestX does inherit that broken code, thus its tests fail. Exactly what we wanted!