EXPECT_CALL without mock in Google Test - c++

Is there any way to test a function call via GoogleTest for c++ without creating mock object, e.g. we have the following production code:
if (a)
method(x);
I would like to test whether the method will be called in the case a is True and a is False. I would like to construct a test that does exactly the same what Google Test's EXPECT_CALL does, but EXPECT_CALL works only with the mock object's method. In my case I would prefer not to use a mock (there is no need to create any object).

As state here,
It's possible to use Google Mock to mock a free function (i.e. a C-style function or a static method). You just need to rewrite your code to use an interface (abstract class).
Their "It's possible" is misleading, as you have to rewrite code to use class (abstract, or provided by template), and so no longer use free functions.

If you are trying to fake a free function, you may want to look into the Fake Function Framework (fff). It allows you to replace free functions with fake implementations that can be used in a similar way to GoogleMock.
It works seamlessly with GoogleMock and GoogleTest.

Related

Is there a way to mock only part of an object in Dart with Mockito?

I am currently trying to develop test-driven with Flutter and Dart.
I have an object that has two methods of which the first one does an http call and the second one calls the first method.
In order to test the first function I mock the dependencies of the that function (namely the http call).
Now I want to test the second method, but I was not able to find a way to mock only the first function while keeping the rest of the object intact. As a result I can only mock the dependencies of the first method again which results in the entire function being executed all over. This goes against the whole purpose of unit testing.
It seems like there is only an all or nothing approach when it comes to mocking objects. I wonder how one is to go about a case where some object is reliant on methods on the same object.
Using Fake and Mock does not allow me to call the original method. spy is deprecated and assigning a mock function to one of the functions does not work since Dart does not allow me to reassign a method.
I found a way to solve my problem. According to this link mentioned in the comments "[t]esting with real objects is preferred over testing with mocks". In my case I just subclassed the main object I was testing and replaced the (second-)method that I was not testing. This seems to do the trick.

Mocking a function call inside a constructor

I have built a file manager(basically reads/writes) class I am trying to unit test. The file format basically belongs to a third party for which I have third party function calls in the constructor. I call all third party calls through wrapper methods
My question is this: Before starting to unit test any method in the class I am trying to instantiate the constructor which looks something like this:
Filemanager::Filemanager{
if(wrapperfoo()){
file->open() //for writing
}
initialise();
}
Now I have a mock class MockManager to mock Filemanager. When I am trying to instantiate MockManager,
I need to mock wrapperoo to return true. However, since the manager itself is not instantiated yet, the EXPECT_CALL fails. Since the EXPECT_CALL has to be placed before the new MockManager()
MockManager *mgr;
EXPECT_CALL(*mgr, wrapperfoo()).Return(true) // Crashes here.. Obviously!!
mgr = new MockManager();
How can I handle this case?
I see no chance for this to work, you are forced to build yourself a workaround. You already gave the explanation yourself.
In principle, mocking isn't designed for what you want to achieve, it is designed for testing components in their behavior to an API or interface, where you mock the interface (API) for the component and not vice versa (https://www.youtube.com/watch?v=dLB2aDasVTg&list=PL_dsdStdDXbo-zApdWB5XiF2aWpsqzV55&index=4, very good explanation). In this example you wouldn't use mocking for internal calls (from the contructor), rather in the test case of another component that requests to get the return type from wrapperfoo().

Behavior of doReturn-when and when-thenReturn with mocked vs spied object

When using a spied object as test subject, If we don't want to call nested methods inside the method we are testing, Which of these (doReturn-when or when-thenReturn) can be used to mock those nested methods?
Is there a way to avoid getting invoked the real methods inside the method we are going to test?
In fact doesn't matter if you use doReturn-when or when-thenReturn method for this specific case, because considering a #Spy you will always call the real method.
You can avoid entering other methods by mocking them, but if you are using just Mockito it will be a problem (it doesn't have this approach, but PowerMock does). Particularly I disagree with this approach, because we are being too intrusive in our tests and private flow is a part of the whole flow, but you can do something like this:
SomeService mock = spy(SomeService.class);
doReturn(1).when(mock, "getNumber", ArgumentMatchers.anyInt());
For more details, you can verify PowerMock's official documentation. Also, is nice to know some basic unit testing concepts (stubs, mocks and so on).

Not Call dependency in Mockito

I have below code, just putting one scenario here.
class A{
public JSONObject m1(type1,type2,type3){
callmethod2(type3);
}
public Map callmethod2(type3){
//some jobs
return myMap;
}
}
#Test
assertequals(JSONObjectTest,m1(type1,type2,type3))
In my test, I am creating a mock with dummy data and passing them to actual function type1,type2,type3 Now there is callmethod2(type3) as a dependency so i do not want to execute that method. so in my test case i written
when(mockA.callmethod2(any(type3.class))).thenReturn(mockMap);
But i can see my callmethod2 is getting execute, how can i solve this and set some expected result for that method in my test case, so it will not execute.
Your code scenario at the time I am writing this is a little incomplete, but I will try to read between the lines. I assume you are somewhere creating a mock instance of class A. I am also assuming you are using that mocked instance to invoke the instance method "m1".
If either of these things are not true, then you will have problems. If you do not create a mock instance, then the "when(...)" clause will not function properly, and in fact while you are invoking the "when" clause you will also actually be invoking the real (i.e., unmocked) instance of A.m1(). The same will be true if you properly mock A but then don't use the mocked instance in the "when" clause, or if you don't use the mocked version in your execute/assert statement(s).
But the bigger problem is that if you actually ARE properly creating and using a mock of A, then even the default mocked functionality of method "m1" becomes empty -- do nothing. It would never get executed. The only way to do what you seem to be proposing is to use what Mockito calls "partial mocking", using a Spy. You instantiate a real instance of A, then wrap it in a Spy to make a "Spied"-instance of A. Now the Spied instance of A inherits all of the default implementations of methods, and you can mock out specific methods if you like. You then must use the spied instance in both yur "whe(...)" clauses as well as your execute/assert statements.
But even that endeavor is questionable. You should try to test classes as a whole rather than mocking out partial behavior. In general (practically a rule),you should either mock nor spy the class under test. If you see a need to do so then there is probably a coherency problem with your class, and it is pointing to design issues or a misunderstanding of good testing practices.

How to avoid duplicate code when using mocks in unittests

I am using dependency injection to supply mocks for code outside of my class under test. I find myself writing alot of the same code over and over as I need to mock out AuthProvider, ConfigurationManager, etc. which are used in the method I want to test. The method contains branches (if-then-else) and therefore I have multiple tests in place to test all execution paths of the method. I am instantiating each of the mocks several times (once in each test method) but am wondering if this is the wrong way around?
Also I am putting up expectations for the mocks and preset responses which evidently are mostly copy-paste as such calls as to AuthProvider.Authenticate() are called in every method
In each method I setup a mock repository and at the end of each method I verify the mock repository. Should I prehaps have some sort of factory for creating these mocks along with setting their expectations and return values and if so how?
For implementation of mocks I am using RhinoMocks.
"instantiating each of the mocks several times" is not a problem. Objects are free.
Just be sure you aren't defining the mock classes numerous times. Classes are expensive.
Also, you have a "setUp" method in a TestCase that allows you to create a fixture that is used by all tests. Yes, it's rebuilt for each test. No, that's not a problem unless it's painfully slow.
Assuming you're using NUnit, you can use instance variables for your Mocks and reset them in Setup/Teardown. If you see repeated patterns then do what you do with production code: refactor and extract helper methods that express what you're trying to achieve (if there's no commonality at all, then there's a problem with the design of the production code).
If there are significant divisions in setup, consider writing more than one test class for your production class.
Finally, think about whether your production class is just too busy and some of the behaviour ought to be extracted out to a helper object.
Listen to the Tests!
Here is my take..
I would not use mock in the case... I would use a factory method to return a fake implementation of the class and use dependency injection to use this implementation instead.. this way you would avoid duplication and can reuse this implementation again n again... again this factory implementation need to be refactored properly i.e., no duplication..
Mocks, I guess should be used when you are testing some dynamic behavior.. something like.. did a method in sub-system was called when I perform some action on SUT.. and later on call verify() to verify this behavior... there is also a good article on Martin Folwer bliki Mock Aren't Stubs
You might want to look at using the AAA style of test so that you have multiple tests with a common setup. Here's a decent example.
Record and Replay frameworks like EasyMock fail if you dont set an expectation on a mock call. But frameworks like Mockito simply record all calls and let you verify only the ones that matter. So you dont have to set expectation on all methods in all tests.
And coming back to your Problem of instantiating Mocks in each test method, there's a better way than using setUp() method. Mockito provides a #Mock annotation. So you declare your variables(as fields) like:
#Mock Repository repositoryMock
and just call initMocks() in setUp(). All mock objects declared are automatically available in your tests without explicitly creating Mocks.