Groovy mock Java class with parameters

I am trying to use groovy MockFor and proxyDelegateInstance to mock a java class with constructor options, but I cannot figure out what is right. My Java class is as follows:

class MyJavaClass { private MyObject myObj public MyJavaClass(MyObject myObj) { this.myObj = myObj; } } class MyGroovyTest { @Test void testMyJavaClass() { def mock = new MockFor(MyJavaClass) MyJavaClass mjc = new MyJavaClass() def mockProxy = mock.proxyDelegateInstance([mjc] as Object[]) // if I pass mockProxy to anything, I get an error that a matching // constructor could not be found. I've tried variations on the args // to proxyDelegateInstance (such as using mjc as a single arg rather than // an array of one element) } } 

Can I do it in groovy? And if so, how can I do this?

thanks jeff

+4
source share
2 answers

The problem was that the class mocking the class was a class, not an interface. To use the proxyDelegateInstance method, you must use the interface type (or the groovy class). The proxy class is not actually of type MyJavaClass, but it is a proxy server, and groovy duck print can handle this, while Java cannot.

+5
source

I cannot say why your code above does not work, but there are several ways in Groovy to make fun of Java classes without using MockFor . For example, if you want to intercept all calls for an object, you can implement invokeMethod in a class metaclass, for example.

 class SomeJavaClass { // methods not shown } def instance = new SomeJavaClass() instance.metaClass.invokeMethod = {String name, args -> // this will be called for all methods invoked on instance } 

Alternatively, if you just want to provide an object that supports SomeJavaClass method SomeJavaClass , you can use either Map or Expando with properties where:

  • property name names correspond to method names
  • proprerty values โ€‹โ€‹are locks that take the same parameters as methods

If you can provide a little more information about how the layout is used, maybe I can offer some more specific suggestions.

+4
source

Source: https://habr.com/ru/post/1300763/


All Articles