Mockito matcher doesn't recognise abstract classes in arguments - unit-testing

this is a sample code
when(someObject.someMethod(any(AbstractClass.class)).thenReturn(mockvalue);
in the above code, it isn't recognising the argument any(AbstractClass.class) and it calls the real method instead of returning the mock value.

I am sorry, but you are on the wrong track there.
any( SomeClass.class ) does NOT do what you believe it does. It especially does NOT check if the argument is a SomeClass, see the Javadoc:
Any kind object, not necessary of the given class.
The class argument is provided only to avoid casting.
If you have a look at the Any class, you will see why:
public boolean matches(Object actual) {
return true;
}
So, ANY argument (as the name implies) will be accepted there. In your case, this means that IF the method someMethod on that specific someObject is called, it WILL return the mockvalue, no matter what the actual argument is.
This implies that your problem is somewhere else entirely, for example ...
Your mock is not correctly injected into the class you are testing (so that the class is using another object and not the mock)
The method in question isn't actually called (for example there could be another one with a similar signature, etc.).
Hard to say without code. I would ask a new question but provide more code this time.

Related

Using C++ Classes to handle commonly used parameters

My team works on an HTTP web server in C++. The codebase has aged over time, and has a widespread problem of 12+ parameters being passed to every function.
A fake example: We need to build a Car, but in order to do that, we have the following function:
MaybeBuildCar(engine_params, steering_params, interior_params, fuel_params, available_inventory, parts, &debug);
Someone on our team has proposed that we create a wrapper CarBuilder class whose constructor takes in the params and "stateful" objects like available_inventory, then has a separate function for BuildCar as follows:
CarBuilder car_builder(engine_params, steering_params, interior_params, fuel_params, available_inventory, &debug);
auto car = car_builder.BuildCar(parts);
Personally, I don't see much value in having a class with a single public function that is always called. We'll always need these parameters, and we'll always need the parts, so this just adds more steps to build the car. It could even add confusion, as now a user of CarBuilder must know to both construct it and call BuildCar.
Admittedly, this simplifies our helper functions within car_builder.cc, as they also require passing these params, but to me that's misusing what a class is for: maintaining state.
Is creating this CarBuilder a misuse of the class, or is simply cleaning up function signatures a valid use? Does anyone have any suggestions on how to tackle this problem?
Minimizing function parameters can be a blessing for heavily used functions in a performance-sensitive environment:
If you pass 6 references to a function, that is 6 pointer copies pushed to the stack;
If you pass a single CarBuilder, it is one "reference-that-contains-6-other-references".
It depends on your situation.
you could define a class that contains all parameters and in each function just passed this object.
struct CarComponent
{
public:
EngineParams engine_params;
SteeringParams steering_params;
InteriorParams interior_params;
FuelParams fuel_params;
AvailableInventory available_inventory
};
MaybeBuildCar(car_component);
other_function(car_component);
Advantage:
Function's signature is decoupled from changing members of the struct (CarComponent). easy to change.
Refactor all the parameters in each function with a specific object. it prevents repetition and it becomes easier to read the code.

How to test (in google test) that a function is called with the correct parameters

I have a class and this class has a method ("original_method") that uses two objects of different types. In this method there are two calls: one call to a method of the first object that returns a value which is then used for calling a method of the second object. I was wondering what is the correct way of unit testing such behavior (using google-test). Specifically, I want to test that the argument provided to the second object is indeed the value returned from the first.
Currently I achieve this using parametrized tests - the code below shows what I do:
TEST_P(SomeTestSuite, checkingIfCalledWithTheRightArgument)
{
EXPECT_CALL(*obj1, get_some_value()).WillOnce(Return(name_of_value));
EXPECT_CALL(*obj2, do_a_calculation(name_of_value));
obj0->call_original_method();
}
I have a fixture for my original class under testing, i have mocks for obj1 and obj2, I provide a value for "name_of_value" in the parameters and the test works.
My problem is that this doesn't seem to be the correct way, I believe I shouldn't have to pass a parameter to check such a functionality. I would appreciate if somebody could explain to me how i should have approached the problem.
Thank you.
EDIT:
I think I could do:
TEST_F(SomeTestSuite, checkingIfCalledWithTheRightArgument)
{
EXPECT_CALL(*obj1, get_some_value());
auto name_of_value = obj1->get_some_value();
EXPECT_CALL(*obj2, do_a_calculation(name_of_value));
obj0->call_original_method();
}
but I'm not sure if this captures (or actually tests) the original behaviour...

How to create custom matchers in Mockito?

I am using Mockito for unit testing. And there are many matchers like anyString(), anyBoolean() in Mockito. But suppose if I have a custom enum like
Enum LoginType.java
//LoginType.java
public enum LoginType {
FACEBOOK,
EMAIL,
GOOGLE
}
In one of the method arguments I need to pass an instance of LoginType. How do I pass the argument without explicitly passing LoginType.FACEBOOK or LoginType.GOOGLE. Something like anyString(). Any hint in that direction will be useful.
For any behavior, just calling Matchers.any() may be good enough on Java 8. That's when parameter type inference came out.
You might also choose Matchers.any(LoginType.class), which has pure any() behavior in Mockito 1.x but will provide type checking in Mockito 2.0 and beyond. In either case, passing in the class literal will help Java get the type information you need for inference.
For related problems:
If you have a generic type, the class literal isn`t enough either; you need to specify it as an explicit method parameter:
Matchers.<YourContainer<YourType>>any();
...or extract to a static helper method, which you need to do instead of a constant or local variable because Mockito matchers work via side effects:
public static LoginType anyLoginType() {
return Matchers.any();
}
Finally, for future readers who might be here to implement custom matching logic, look for Matchers.argThat or MockitoHamcrest.argThat to adapt a Hamcrest-style Matcher object into a Mockito method call.

JMock, What should you do when the mock object gets casted to a concrete class?

Not sure how I should be asking the question, but when I define my mock objects, and somewhere in the code it attempts to cast it to a different type the test throws me
$Proxy6 cannot be cast to ...
How does one solve this problem?
Does this class really need to be mocked? I usually mock services and use concrete classes for value types passed in.
One thing you can do is outlined here: define an interface in your test.
If it really needs to be mocked and you can't do the above you could provide your own implementation which does what you want the mock to do e.g. records values passed in, methods called, returns the values you want etc. and assert what you need at the end - that might be a lot of work though.
Lastly, is this pointing you towards some unidentified interfaces in your design or that the code under test needs some refactoring?
As always, the test is telling you something about your design. Why is the code trying to cast the object? Could you give us more detail?

Is it OK to pass parameters to a Factory method?

One of the ways to implement Dependency Injection correctly is to separate object creation from business logic. Typically, this involves using a Factory for object creation.
Up until this point, I've never seriously considered using a Factory so I apologize if this question seems a little simplistic:
In all the examples of the Factory Pattern that I've run across, I always see very simple examples that have no parameterization. For example, here's a Factory stolen from Misko Hevery's excellent How To Think About the "new" Operator article.
class ApplicationBuilder {
House build() {
return new House(new Kitchen(
new Sink(),
new Dishwasher(),
new Refrigerator())
);
}
}
However, what happens if I want each house that I build to have a name? Am I still using the Factory pattern if I re-write this code as follows?
class ApplicationBuilder {
House build( const std::string & house_name) {
return new House( house_name,
new Kitchen(new Sink(),
new Dishwasher(),
new Refrigerator())
);
}
}
Note that my Factory method call has changed from this:
ApplicationBuilder builder;
House * my_house = builder.build();
To this:
ApplicationBuilder builder;
House * my_house = builder.build("Michaels-Treehouse");
By the way: I think the concept of separating object instantiation from business logic is great, I'm just trying to figure out how I can apply it to my own situation. What confuses me is that all the examples I've seen of the Factory pattern never pass any parameters into the build() function.
To be clear: I don't know the name of the house until the moment before I need to instantiate it.
I've seen quite a lot of examples that use a fixed set of arguments, like in your name example, and have used them myself too and i can't see anything wrong with it.
However there is a good reason that many tutorials or small articles avoid showing factories that forward parameters to the constructed objects: It is practically impossible to forward arbitrary number of arguments (even for a sane limit like 6 arguments). Each parameter you forward has to be accepted as const T& and T& if you want to do it generic.
For more complicated examples, however, you need an exponentially growing set of overloads (for each parameter, a const and a nonconst version) and perfect forwarding is not possible at all (so that temporaries are forwarded as temporaries, for example). For the next C++ Standard that issue is solved:
class ApplicationBuilder {
template<typename... T>
House *build( T&&... t ) {
return new House( std::forward<T>(t)...,
new Kitchen(new Sink(),
new Dishwasher(),
new Refrigerator())
);
}
};
That way, you can call
builder.build("Hello", 13);
And it will return
new House("Hello", 13, new Kitchen(new Sink(...
Read the article i linked above.
Not only is is acceptable, but it's common to pass parameters to a factory method. Check out some examples. Normally the parameter is a type telling the factory what to make, but there's no reason you can't add other information you need to build an object. I think what you're doing is fine.
I can't see why it would be wrong to add this parameter to your factory. But be aware that you shouldn't end up adding many parameters which might not be useful to all objects created by the factory. If you do, you'll have lost quite a lot of the advantages of a factory !
The idea of a factory is that it gives you an instance of a class/interface, so there is nothing wrong with passing parameters. If there were, it would be bad to pass parameters to a new() as well.
I agree with Benoit. Think of a factory for creating something like sql connections though, in a case like this it would be necessary to pass information about the connection to the factory. The factory will use that information to use the correct server protocol and so on.
Sure, why not..!?
The nice thing about passing parameters is that it allows you to hide the implementation of the concrete object. For example, in the code you posted you pass the parameters to the constructor. However, you may change the implementation so that they get passed via an Initiailze method. By passing parameters to the factory method you hide the nature of constructing and initializing the object from the caller.
Take a look at Loki::Factory, there's an implementation very much like it coming to Boost as well, however. Some example code i regularly use in different flavors:
typedef Loki::SingletonHolder< Loki::Factory< Component, std::string, Loki::Typelist< const DataCollection&, Loki::Typelist< Game*, Loki::NullType > > > > ComponentFactory;
This might seem a bit weird at first sight, however let me explain this beast and how powerful it really is. Basically we create a singleton which holds a factory, the out most parameters are for the singleton, Component is our product, std::string is our creation id type, after this follows a type list of the params which is required for creation of Components ( this can be defined using a macro as well for a less verbose syntax ). After this line one can just do:
ComponentFactory::Instance().CreateObject( "someStringAssociatedWithConcreteType", anDataCollection, aGamePointer );
To create objects, to register one just use ComponentFactory::Instance().Register();. There's a great chapter on the details in the book Modern C++ Design.