Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy mock Java class with parameters

I'm trying to use groovy's MockFor and proxyDelegateInstance to mock a java class with constructor parameters, but I can't seem to get it right. My Java class looks like:

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 actually do this in groovy? And if so, how can I do it?

thanks, Jeff

like image 789
Jeff Storey Avatar asked Jan 23 '23 14:01

Jeff Storey


1 Answers

The problem was that the class being mocked was a class and not an interface. In order to use the proxyDelegateInstance method, the an interface type needs to be used (or a groovy class). The proxy class is not actually of the MyJavaClass type but is a proxy and groovy's duck typing can handle that while Java cannot.

like image 173
Jeff Storey Avatar answered Feb 04 '23 00:02

Jeff Storey