Monday, January 14, 2008

Mocking Groovy Objects with EasyMock in Java

I mentioned before that I needed to do some unit testing of a class that I was targeting in Groovy with come unit tests in Java. In Java, I am using EasyMock to mock out the collaborators. I am dealing with one collaborator, an interface, that looks like this (Groovy):


interface FileSystem {
...
def uploadFile(inputStream, destinationPath)
...
}

For the purposes of this unit test, I didn't care what got returned, so I setup the expectation like this (Java):

desintationFileSystem.uploadFile(streamForFile1, "someDir\\someOtherDir\\file1.jpg");

Running the test, I was greeted with this message:

java.lang.IllegalStateException: missing behavior definition
for the preceeding method call
uploadFile(EasyMock for class java.io.FileInputStream,
"someDir\someOtherDir\file1.jpg")
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:27)
...

That's when I remembered something fundamental to groovy... the 'def' type means variable return type. For Java, that translates into Object. To make the test run, I either needed to explicitly change the return type on the interface to be void, or simply setup the EasyMock expectation to return a value. Since I didn't want to change the interface, I chose to specify the return value in the expectation.

No comments: