How to create custom matchers in Mockito? - unit-testing

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.

Related

EXPECT_CALL without mock in Google Test

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.

Mockito matcher doesn't recognise abstract classes in arguments

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.

Delphi - Testing if events are assigned to methods, but without overriding for every delegate type

I have to unit tests some forms in Delphi. My boss wants me to write tests to check if events are assigned. There are so many that we have to run some checks on them.
For example, I want to check that
TMyForm.OnCreate = TMyForm.FormCreate.
To do this, I wrote :
function TFMaitreTest.SameMethod(const Method1, Method2: TNotifyEvent; msg : string = ''): boolean;
begin
Assert.IsTrue(TEqualityComparer<TNotifyEvent>.Default.Equals(Method1, Method2), msg);
end;
But using this way, I have to override the SameMethod for every kind of event delegate : TNotifyEvent, TDataSetEvent, ...
I then thought of using generics, as such :
function TFMaitreTest.SameMethod<T>(const Method1, Method2: T; msg : string = ''): boolean;
But this does not compile. TEqualityComparer needs some Generic constraint, but a generic constraint cannot be defined for a procedure of object. Using TMethod as a constraint does not work either. Maybe there's a way here, but I have not found it.
Then, I thought of changing approach altogether using Rtti. I want to compare the methods using Rtti, but for that, I have to know the name of the method with a string.
RttiType.GetMethod(methodName)
Here, methodName is a pure string. If we refactor and methodName becomes MyMethod, we're kind of screwed and have to check manually everywhere this string is used. We would like to have compile time errors. It's less error prone.
C# has the concept of lambda expressions which is very powerful for these kind of scenarios :
See Get the name of a method using an expression
How can I write a more generic way of testing if an event property is assigned to a specific procedure, without having to write a method for every event kind ?
Thank you for your help.
Since you are using the DUnitX Assert type you should use its AreEqual<T> method which does exactly what you want - you have to specify the generic type parameter though and cannot let the compiler infer it:
Assert.AreEqual<TNotifyEvent>(myForm.OnCreate, myForm.FormCreate);

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?

How do you create a mock object without an interface class in AMOP?

I'm just getting into Test Driven Development with mock objects. I can do it the long way with UnitTest++, but now I want to try to minimize typing, and I'm trying to use AMOP mock framework to do the mocking.
AMOP states:
The main differences between AMOP and other mock object library is that,
users DO NOT need to implement the
interface of the object which to
mock...
However, I can't figure this out. The basic usage page still shows a IInterface class. Anyone able to do it without using an interface class?
For what I've seen in the documentation, it actually doesn't need the mock object to implement any interface. The mocking object is constructed based on the original object's interface, but not by inheritance, but as a parameter of the class:
TMockObject<IInterface> mock;
No inheritance here, and TMockObject doesn't get tied to any interface by inheritance. Then, adding mock methods to be implemented by the mock object:
mock.Method(&IInterface::SimpleFunction);
mock.Method(&IInterface::SimpleFunctionWithAlotParams);
((IInterface*)mock)->SimpleFunction();
((IInterface*)mock)->SimpleFunctionWithAlotParams(0, 0, 0, 0, std::string());
Again, the object mock does not actually inherit the interface. It may redefine the conversion operator to IInterface* (it will return an internal IInterface object).
I don't see many advantages in not inheriting the interface, but anyway. I would have preferred some template as member function of TMockObject to give more meaning to that ugly cast (not tested, just an idea):
template <typename I>
I* as(void)
{
return m.internal_interface_pointer_;
}
so you could write something like:
mock.as<IInterface>()->SimpleFunction();
but still...
This is the first time I hear that a mock framework doesn't need an interface to crate mock objects. Every other do. Must be a bug in the documentation.