Mockito Matching parameterized method with multiple interface - mockito

Hi I've created a nice interface for my service which accepts object implementing 2 interfaces, but now I have difficulties to create a matcher for this interface.
Anyone has any idea how to create a matcher for the following?
<T extends HasDocumentTags & HasResources> ResponseEntity<Void> setDocumentMetadata(T t);
Just an any() wouldn't help here, as the method is overloaded already twice
ResponseEntity<Void> setDocumentMetadata(List<Document> attachments);
ResponseEntity<Void> setDocumentMetadata(ApproveDocumentsCommand<?> command);
Now I'm trying to mock the service and defining an answer
when(service.setDocumentMetadata( ??? ).thenReturn(anAnswer);
I just can't figure out the right matcher for any(), eq() or whatever will be working.
Or am I trying thing which aren't possible (in java8)?
Can you help me?

use any for type Document and ApproveDocumentsCommand:
when(service.setDocumentMetadata(any(Document.class)).thenReturn(anAnswer1);
when(service.setDocumentMetadata(any(ApproveDocumentsCommand.class)).thenReturn(anAnswer2);
I this any(Document.class) and any(ApproveDocumentsCommand.class) should be enoght.
also you can use ArgumentMatcher , if you need check type for arguments with some extra checks:
when(service.setDocumentMetadata(argThat(new MyCommonMatcher<>())))
.thenReturn(responseEntityOk);
when(service.setDocumentMetadata(argThat(new MyDocumentMatcher<>())))
.thenReturn(responseEntityOk);
when(service.setDocumentMetadata(argThat(new MyApproveDocumentsCommandMatcher<>())))
.thenReturn(responseEntityOk);
class MyCommonMatcher<T extends HasDocumentTags & HasResources>
extends ArgumentMatcher<T>{
#Override
public boolean matches(Object argument) {
return (argument instanceof HasResources) && (argument instanceof HasDocumentTags);
}
}
class MyDocumentMatcher<T extends HasDocumentTags & HasResources>
extends ArgumentMatcher<T>{
#Override
public boolean matches(Object argument) {
return argument instanceof Document;
}
}
class MyApproveDocumentsCommandMatcher<T extends HasDocumentTags & HasResources>
extends ArgumentMatcher<T>{
#Override
public boolean matches(Object argument) {
return argument instanceof ApproveDocumentsCommand;
}
}

Related

Closure Coercion not working in certain case

I'm calling a Java method from Groovy which expects an instance of a SAM interface as a parameter.
Normally Groovy is happy with passing in a closure in these cases, and will coerce it accordingly HOWEVER in this case, the interface extends another one and overrides the single method.
Note - It still only has one method, but it's been overriden.
In this instance Groovy doesn't automatically coerce the closure and the only way I seem to be able to call it is by using "AS".
I'm publishing an API to help kids to learn code and really don't want them to have to use "AS" because it would complicate things.
Here's some code that shows the issue...
Java
public interface BaseHandler<T> {
public void handle(T test);
}
public interface Handler extends BaseHandler<String> {
public void handle(String test);
}
public class LibraryClass {
public void method(Handler handler) {
handler.handle("WORLD!");
}
}
Groovy
LibraryClass bar = new LibraryClass();
bar.method({ name -> println "HELLO " + name})
Error
Caught: groovy.lang.MissingMethodException: No signature of method: Bar.doIt() is applicable for argument types: (testClosures$_run_closure1) values: [testClosures$_run_closure1#fe63b60]
Any help on how to get around this without using "AS" would be hugely appreciated
Groovy wants to implement the interface by coercion, but doesn't know which interface method it should implement. As there are 2:
the handle(String test) and a second one: handle(String test) (of the baseHandler)
The solution is to remove the handle(String test) from the handler (it adds nothing as the BaseHandler posesses this method already thanks to the generics).
Like this it works correctly:
public interface BaseHandler<T> {
public void handle(T test);
}
public interface Handler extends BaseHandler<String> {
}
public class LibraryClass {
public void method(Handler handler) {
handler.handle("WORLD!");
}
}

How does Groovy select method when a user-defined method conflicts with a GDK method

I wrote the following Java classes:
package com.example;
class MySet extends java.util.AbstractSet {
#Override public java.util.Iterator iterator() { return null; }
#Override public int size() { return 0; }
}
interface ToSet { MySet toSet(); }
public class MyList extends java.util.AbstractList implements ToSet {
#Override public Object get(int index) { return null; }
#Override public int size() { return 0; }
public MySet toSet() {
return new MySet();
}
}
and a test in Groovy:
package com.example
class MyTest {
#org.junit.Test
public void test() {
MySet set = new MyList().toSet();
println(set.class);
println(new MyList().toSet().class);
def set2 = new MyList().toSet();
println(set2.class);
}
}
The test run results in:
class com.example.MySet
class java.util.HashSet
class java.util.HashSet
My guess is that in the latter two cases the expression toSet() invokes the GDK's toSet method instead of MyList#toSet, but what is the exact rule about this behavior? Does Groovy's method selection depend not only on receiver and arguments, but also on the context?
One more subtle thing is that if I remove implements ToSet from the Java code above, the test prints class com.example.MySet for all three cases. So I got confused.
In the three examples you mention, your toSet method is never invoked. This is easily verified by adding a print statement to your toSet method in MyList. The reason the first class is printed as MySet is because of the assignment to a variable of the type MySet - Groovy will implicitly cast the HashSet to MySet upon assignment (magic!).
The rest of the behavior is more subtle. When no interface implementation is declared (you remove implements ToSet), Groovy method dispatcher will pick the method implementation on the MyList class, i.e. the method you defined. Apparently, when the interface implementation is defined, the method dispatcher has to choose between the interface implementation (MyList toSet) and the superclass implementation (GDK toSet), and it's choosing the latter (they both have no arguments).

How to use PowerMockito to verify super method is called

I am testing a legacy code that use inheritance method. I am trying to mock super-method
to verity if the super-method is being call or not.
#RunWith(PowerMockRunner.class)
public class HumanTest {
#Test
public void test() throws NoSuchMethodException, SecurityException {
// 1. arrange
Human sut = PowerMockito.spy(new Human());
PowerMockito.doNothing().when((SuperHuman) sut).run(); // SuperHuman is the parent class
// 2. action
sut.run();
// 3. assert / verify
}
}
public class Human extends SuperHuman {
#Override
public void run() {
System.out.println("human run");
super.run();
}
}
public class SuperHuman {
public void run() {
System.out.println("superhuman run");
}
}
I was expecting that "human run" will be printed. But the actual result was none printed.
PowerMockito.doNothing().when((SuperHuman) sut).run(); // SuperHuman is the parent class
This won't work in your case since PowerMockito will mock method of Human even if you made cast.
I checked your code example and could say that it is possible to suppress invocation of super class method with:
Method toReplace = PowerMockito.method(SuperHuman.class, "run");
PowerMockito.suppress(toReplace);
But it seems that method replacment feature does not work for methods of super class:
createPartialMock should support mocking overridden methods in super classes.
So this does not work:
PowerMockito.replace(toReplace).with(new InvocationHandler() {
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Method of superclass has been invoked !");
return null;
}
});
But still you should be able to verify invocation of super method let's say indirectly, by mocking other classes which are invoked in super method only.
For instance check that System.out.println was invoked with "superhuman run" or something like this.

Using DynamicObject (IDynamicMetaObjectProvider) as a component of a static type leads to infinite loop

I'm trying to create a dynamic object that can be used as a component of a static object. Here is a contrived example of what I'm trying to accomplish.
Here is the dynamic component:
public class DynamicComponent : DynamicObject
{
public override bool TryInvokeMember(
InvokeMemberBinder binder,
object[] args,
out object result)
{
result = "hello";
return true;
}
}
And here is a class where inheriting from DynamicObject isn't an option...assume that there is some third party class that I'm forced to inherit from.
public class AStaticComponent : VendorLibraryClass, IDynamicMetaObjectProvider
{
IDynamicMetaObjectProvider component = new DynamicComponent();
public DynamicMetaObject GetMetaObject(Expression parameter)
{
var result = component.GetMetaObject(parameter);
return result;
}
}
The direct usage of DynamicComponent works:
dynamic dynamicComponent = new DynamicComponent();
Assert.AreEqual(dynamicComponent.AMethod(), "hello");
However, forwarding the GetMetaObject through AStaticComponent causes some form of an infinite loop.
dynamic dynamicComponent = new AStaticComponent();
Assert.AreEqual(dynamicComponent.AMethod(), "hello"); //causes an infinite loop
Anyone know why this occurs?
And if it's some baked in behavior of DynamicObject that I cannot change, could someone provide some help on how to create a IDynamicMetaObjectProvider from scratch to accomplish a component based dynamic object (just something to get things started)?
I think the problem is that the Expression parameter passed to GetMetaObject represents the target of the dynamic invocation (i.e. the current object). You are passing the outer object to the call on component.GetMetaObject, so the returned meta object is trying to resolve the call to AMethod on the outer object instead of itself, hence the infinite loop.
You can create your own meta object which delegates to the inner component when binding member invocations:
public class AStaticComponent : VendorLibraryClass, IDynamicMetaObjectProvider
{
IDynamicMetaObjectProvider component = new DynamicComponent();
public DynamicMetaObject GetMetaObject(Expression parameter)
{
return new DelegatingMetaObject(component, parameter, BindingRestrictions.GetTypeRestriction(parameter, this.GetType()), this);
}
private class DelegatingMetaObject : DynamicMetaObject
{
private readonly IDynamicMetaObjectProvider innerProvider;
public DelegatingMetaObject(IDynamicMetaObjectProvider innerProvider, Expression expr, BindingRestrictions restrictions)
: base(expr, restrictions)
{
this.innerProvider = innerProvider;
}
public DelegatingMetaObject(IDynamicMetaObjectProvider innerProvider, Expression expr, BindingRestrictions restrictions, object value)
: base(expr, restrictions, value)
{
this.innerProvider = innerProvider;
}
public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
{
var innerMetaObject = innerProvider.GetMetaObject(Expression.Constant(innerProvider));
return innerMetaObject.BindInvokeMember(binder, args);
}
}
}
#Lee's answer is really useful, I wouldn't have known where to get started without it. But from using it in production code, I believe it has a subtle bug.
Dynamic calls are cached at the call site, and Lee's code produces a DynamicMetaObject which effectively states that the inner handling object is a constant. If you have a place in your code where you call a dynamic method on an instance of AStaticObject, and later the same point in the code calls the same method on a different instance of AStaticObject (i.e. because the variable of type AStaticObject now has a different value) then the code will make the wrong call, always calling methods on the handling object from the first instance encountered at that place in the code during that run of the code.
This is a like-for-like replacement, the key difference being the use of Expression.Field to tell the dynamic call caching system that the handling object depends on the parent object:
public class AStaticComponent : VendorLibraryClass, IDynamicMetaObjectProvider
{
IDynamicMetaObjectProvider component = new DynamicComponent();
public DynamicMetaObject GetMetaObject(Expression parameter)
{
return new DelegatingMetaObject(parameter, this, nameof(component));
}
private class DelegatingMetaObject : DynamicMetaObject
{
private readonly DynamicMetaObject innerMetaObject;
public DelegatingMetaObject(Expression expression, object outerObject, string innerFieldName)
: base(expression, BindingRestrictions.Empty, outerObject)
{
FieldInfo innerField = outerObject.GetType().GetField(innerFieldName, BindingFlags.Instance | BindingFlags.NonPublic);
var innerObject = innerField.GetValue(outerObject);
var innerDynamicProvider = innerObject as IDynamicMetaObjectProvider;
innerMetaObject = innerDynamicProvider.GetMetaObject(Expression.Field(Expression.Convert(Expression, LimitType), innerField));
}
public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
{
return binder.FallbackInvokeMember(this, args, innerMetaObject.BindInvokeMember(binder, args));
}
}
}

I want to know theoretical thing about programming

I'm not sure about one thing. There are two things in object oriented programming.
Constructor
Method
Which one of these can be overloaded and which one overridden?
Thanks!
both can be overloaded.
overloading means having two or more methods or constructors with exactly same name but different signatures. some thing like :
public myClass(String a){}
public myClass(Double d){}
or for methods :
public void aMethod(String s){}
publis int aMethod(Double d){
return 0;
}
edited :
bebin, overriding usually comes with inheritance , when the super class implements a method but the subclass needs to implement that method in other way like :
in super class:
public int doSomething(){
return a+2;
}
but in subclass :
#override
public in doSomething(){
return a*2;
}
and about constructor overriding the following line are from CollinD and i am quoting it :
"Constructors are not normal methods and they cannot be "overridden". Saying that a constructor can be overridden would imply that a superclass constructor would be visible and could be called to create an instance of a subclass. This isn't true... a subclass doesn't have any constructors by default (except a no-arg constructor if the class it extends has one). It has to explicitly declare any other constructors, and those constructors belong to it and not to its superclass, even if they take the same parameters that the superclass constructors take.
The stuff you mention about default no arg constructors is just an aspect of how constructors work and has nothing to do with overriding."
That may depend on the language, but theoretically both can be both overloaded and overridden.
C# examples of everything:
class Parent {
protected string Name;
public Parent(string name) {
this.Name = name;
}
public Parent(string firstName, string lastName) {
this.Name = firstName + " " + lastName;
}
public virtual string GetName() {
return this.Name;
}
}
class Child : Parent {
public Child(string firstName) : base(firstName, "Doe") {}
public override string GetName() {
return this.Name = " Jr.";
}
public string GetName(string prefix) {
return prefix + " " + this.GetName();
}
}
This illustrates constructor and method overriding and constructor and method overloading.
You can overload and override both constructors and methods. (I think constructors are really just a special kind of method.)
Overriding allows a subclass to replace the implementation of its parent class.
Overloading allows you to create a different versions of a method that take different parameter lists.

Resources