I have been using Mockito for unit testing the action classes in my code. I have been successful in performing end to end test for almost every action but one. This particular action depends on ActionContext for retrieving the session and I must remind you that it will not be possible to replace the existing code with the implementation of SessionAware and setSessionAttributes().
Basically, the error I get is a null pointer exception on Action Context and even after tremendous investigation, the exception remains as it is.
The particular code which causes this error is :
book = (Book) ActionContext.getContext().getSession().get("sessionKey");
and the error log I get is :
java.lang.NullPointerException
at com.syb.ao.test.ApplyPromoDetailsTest.prepareTests(ApplyPromoDetailsTest.java:72)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.internal.runners.MethodRoadie.runBefores(MethodRoadie.java:132)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:95)
I have tried just about everything I could to get this running but just cannot find a solution.
Related
I want to test a function in which a new View is created within TornadoFX. When i call the function however, i get this error.
java.lang.ExceptionInInitializerError
at tornadofx.ControlsKt.button(Controls.kt:190)
at tornadofx.ControlsKt.button$default(Controls.kt:190)
at view.PeopleMenuView$setupTopBox$1$1.invoke(PeopleMenuView.kt:33)
at view.PeopleMenuView$setupTopBox$1$1.invoke(PeopleMenuView.kt:8)
at tornadofx.LayoutsKt.vbox(Layouts.kt:388)
at tornadofx.LayoutsKt.vbox$default(Layouts.kt:103)
at view.PeopleMenuView$setupTopBox$1.invoke(PeopleMenuView.kt:31)
at view.PeopleMenuView$setupTopBox$1.invoke(PeopleMenuView.kt:8)
at tornadofx.LayoutsKt.hbox(Layouts.kt:384)
at tornadofx.LayoutsKt.hbox$default(Layouts.kt:96)
at view.PeopleMenuView.setupTopBox(PeopleMenuView.kt:29)
at view.PeopleMenuView.<init>(PeopleMenuView.kt:15)
at presenter.MainMenuPresenter.managePeoplePressed(MainMenuPresenter.kt:11)
at presenter.TestMainMenuPresenter.testManagePeoplePressed(TestMainMenuPresenter.kt:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.IllegalStateException: Toolkit not initialized
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:273)
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:268)
at com.sun.javafx.application.PlatformImpl.setPlatformUserAgentStylesheet(PlatformImpl.java:550)
at com.sun.javafx.application.PlatformImpl.setDefaultPlatformUserAgentStylesheet(PlatformImpl.java:512)
at javafx.scene.control.Control.<clinit>(Control.java:87)
... 36 more
It is because a new instance of a view is created in the function. The simplified code looks like this:
fun managePeoplePressed() {
view.replaceWith(PeopleMenuView())
}
When i call the method from a test, i get the error. I googled around but there's not much to find about this.
I want to be able to test methods that create a view. Thank you.
In general: you don't want to test UI views. Hold tight, I'm still going to tell you how. I just want you to know it's a rare case that can be indicating design problems.
Without TestFx such tests are quite difficult to write. With TestFx they're easier, but still both very slow and very fragile, and you'll have to take extra steps in any of the standard CI environments to allow them to run on the build boxes, which are normally not equipped to run JavaFx and not equipped with virtual displays.
The biggest problem you (and TestFx) encounter is with getting your threads right inside the test. The tests are on one thread. The visual parts of JavaFx are on another. Your own application and JavaFx itself frequently pour their tasks into Platform.RunLater(), and if you don't account for the emptying of that queue, you'll get results that are either uniformly wrong or, worse, flicker-y. Sleeps work in some cases, but a) are sleeps and slow you down, and b) won't work as well when you run on a slower box, like a low-configured windows box in the cloud.
Back to your general question: It likely means that your intra-View connections are complex, where UI component X depends on UI component Y. Broadly, you want UI component X to depend on properties in the Model, and you want UI component Y to depend on properties in the Model, and you want the Model handling the complex interactions between properties. TornadoFx has direct support for this, and Model classes don't need the UI running to be tested. For some cases, the Controller is the place to put that interconnected logic, but that's relatively rare. Most of what I do just doesn't call for that, but it does call for Model classes. The key insight that (Model != Domain) is well-supported in TornadoFx's ViewModel and ItemViewModel classes.
Having said all that, if you need robot-control over the view, the way to do it is to use TestFx. If you don't, this is agreeing with and elaborating on Edvin's answer, is to have something like this:
class UiTest {
companion object {
private var javaFxRunning: Boolean = false
fun start() {
StartWith.isUi = true
Errors.reallyShow = false
try {
runJavaFx()
} catch (e: InterruptedException) {
throw RuntimeException(e)
}
}
#Throws(InterruptedException::class)
private fun runJavaFx() {
if (javaFxRunning) return
val latch = CountDownLatch(1)
SwingUtilities.invokeLater {
JFXPanel()
latch.countDown()
}
latch.await()
javaFxRunning = true
}
}
}
In the #BeforeEach or even in individual #Tests, call UiTest.start(), which will only start the javafx one time no matter how many tests need it running.
My actual experience: the JavaFx Component <-> property relationship "just works". That is, I gain very little from testing it, as it's not my code, and it works "every time". What is my code and doesn't work every time is the relationship between the properties. That's why I use ViewModel, put the interactions between properties there, and test them rigorously with microtests, which doesn't require the JavaFx thread to be running. (JavaFx properties use no multi-threading in their callbacks, so addListener targets are called synchronously.) This is particularly handy when you need to be clever with your bindings. Inlining complex JavaFx bindings inside the TornadoFx view builder is a mug's game. Extracting them to the model is dead-easy.
I learned all this by trial and error. There is a third approach, described in this stack overflow, that can be made to work. It amounts to making 100% of your tests run in the JavaFx thread. I found it difficult, because most of my work isn't on that thread in production. Basic JUnit test for JavaFX 8
Good luck, and reach out if you need more help!
GeePawHill
P.S. Shouts out to Edvin: Great work on TornadoFx. I use it every day.
You need to initialize the JavaFX Toolkit. If you're using TestFX you can make a call to FxToolkit.registerPrimaryStage(), if not you can instantiate a JFXPanel to achieve the same goal.
I'm looking at log4-clj-layout to bring a little order to the mess that is logging in Java. I'd like play around a little with a format function of my own, but I'm failing at getting it to work.
Following the instructions on the page above I started with adding the following to my log4j.properties file:
log4j.appender.console.layout=log4_clj_layout.layout.Layout
log4j.appender.console.layout.FormatFn=json-format
That worked beautifully. Then I added a function, log-test.core/my-format and tried to use that for logging:
log4j.appender.console.layout=log4_clj_layout.layout.Layout
log4j.appender.console.layout.FormatFn=log-test.core/my-format
But now all I get is an error when starting:
(log/warn "foo")
Setting format-fn: log-est.core/my-format
log4j:WARN Failed to set property [formatFn] to value "log-test.core/my-format".
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
...
Clearly I'm missing something, but what?
I defined my format function like this (l is an alias for log4-clj-layout.layout):
(defn my-format [event]
(pr event)
(l/json-format event))
Any and all help would be much appreciated.
I am trying to unit test an old legacy application that uses JFreeChart and I'm trying to create a spy of a JFreeChart object this way:
JFreeChart chart = PowerMockito.spy(ChartFactory.createTimeSeriesChart("Mocked Name", "Date", "Mocked YAxis Name", dataset, true, true, false));
I don't know if it is even valid to create a spy this way, I've only ever done it before with the new operator. But I did try just making a mock like this and got the same error:
JFreeChart chart = Mockito.mock(JFreeChart.class);
Here is the error I'm getting:
java.lang.VerifyError: (class: javax/swing/plaf/metal/MetalLookAndFeel, method: getLayoutStyle signature: ()Ljavax/swing/LayoutStyle;) Wrong return type in function
at javax.swing.UIManager.setLookAndFeel(UIManager.java:554)
at javax.swing.UIManager.initializeDefaultLAF(UIManager.java:1317)
at javax.swing.UIManager.initialize(UIManager.java:1406)
at javax.swing.UIManager.maybeInitialize(UIManager.java:1394)
at javax.swing.UIManager.getDefaults(UIManager.java:633)
at javax.swing.UIManager.getColor(UIManager.java:675)
at org.jfree.chart.JFreeChart.<clinit>(JFreeChart.java:248)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at javassist.runtime.Desc.getClassObject(Desc.java:43)
at javassist.runtime.Desc.getClazz(Desc.java:52)
at org.jfree.chart.ChartFactory.createTimeSeriesChart(ChartFactory.java:1850)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.powermock.api.mockito.internal.invocation.MockitoMethodInvocationControl$1.invoke(MockitoMethodInvocationControl.java:242)
at org.powermock.api.mockito.internal.invocation.MockitoMethodInvocationControl.performIntercept(MockitoMethodInvocationControl.java:260)
at org.powermock.api.mockito.internal.invocation.MockitoMethodInvocationControl.invoke(MockitoMethodInvocationControl.java:192)
at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:123)
at org.powermock.core.MockGateway.methodCall(MockGateway.java:62)
at org.jfree.chart.ChartFactory.createTimeSeriesChart(ChartFactory.java)
at co.ihc.com.heightweight.HeightWeightModuleTests.createChartTest(HeightWeightModuleTests.java:1558)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:88)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:96)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:33)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:104)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Having googled around a bit it looks like it could be due to a compatibility issue between my Java version and the Java version used to compile the jfreechart jar. I'm using Java 6 and here is my Maven dependency for jfreechart:
<dependency>
<groupId>jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.0.8a</version>
</dependency>
Any ideas of how to resolve this? Can I just use a different version of jfreechart and if so, does anyone know which version?
It's been a while, but I finally came back to this questions after I've had much more experience unit testing. The problem came from an instance variable in JFreeChart that was calling a method to instantiate itself. Once I mocked that method, I was able to mock JFreeChart without error.
I'm trying to build a Spring XD (Spring Integration DSL based) sink module using the spring-integration-aws extension. My module looks like so:
#Configuration
#EnableIntegration
public class S3Module {
#Value("${accessKey:myAccessKey}")
private String accessKey;
#Value("${secretKey:mySecretKey}")
private String secretKey;
#Value("${bucket:myBucket}")
private String bucket;
#Value("${remoteDirectoryExpression:dir}")
private String remoteDirectoryExpression;
#Bean
public AmazonS3MessageHandler handle() {
AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
AmazonS3MessageHandler handler = new AmazonS3MessageHandler(credentials, new DefaultAmazonS3Operations(credentials));
handler.setBucket(bucket);
handler.setRemoteDirectoryExpression(new LiteralExpression(remoteDirectoryExpression));
return handler;
}
#Bean
public IntegrationFlow flow() {
return IntegrationFlows.from("input")
.handle(handle())
.get();
}
}
I can successfully package up the module and deploy it. When trying to create the stream with:
xd:>stream create --name s3test --definition "file --outputType=text/plain --dir='/tmp/logs' | s3" --deploy
I get the following exception:
00:25:28,850 1.1.0.RC1 INFO DeploymentSupervisor-0 server.StreamDeploymentListener - Deployment status for stream 's3test': DeploymentStatus{state=failed,error(s)=org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flow' defined in com.test.xd.S3Module: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.integration.dsl.IntegrationFlow]: Factory method 'flow' threw exception; nested exception is java.lang.ClassCastException: com.sun.proxy.$Proxy145 cannot be cast to org.springframework.integration.aws.s3.AmazonS3MessageHandler
...
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.integration.dsl.IntegrationFlow]: Factory method 'flow' threw exception; nested exception is java.lang.ClassCastException: com.sun.proxy.$Proxy145 cannot be cast to org.springframework.integration.aws.s3.AmazonS3MessageHandler
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 36 more
Caused by: java.lang.ClassCastException: com.sun.proxy.$Proxy145 cannot be cast to org.springframework.integration.aws.s3.AmazonS3MessageHandler
at com.test.xd.S3Module$$EnhancerBySpringCGLIB$$8623ddbe.handle(<generated>)
at com.test.xd.S3Module.flow(S3Module.java:49)
at com.test.xd.S3Module$$EnhancerBySpringCGLIB$$8623ddbe.CGLIB$flow$1(<generated>)
at com.test.xd.S3Module$$EnhancerBySpringCGLIB$$8623ddbe$$FastClassBySpringCGLIB$$3453fd21.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309)
at com.test.xd.S3Module$$EnhancerBySpringCGLIB$$8623ddbe.flow(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 37 more
I'm fairly certain I'm missing something simple. Can someone point me in the right direction? Thanks in advance!
Thank you for doing such a work! Yes, definitely we'll introduce somedays out-of-the-box AWS modules to XD.
Your issue is similar to this one: https://github.com/spring-projects/spring-boot/issues/2441#issuecomment-72758919.
To overcome that you just should do:
#Bean
public MessageHandler handle() {
make return type as an interface not target class. That's because Spring Integration JMX exposing feature is switched on by default in XD.
Out of topic: we are going to break SI-AWS soon and make it based on the Spring Cloud AWS. And I think that that AWSCredentials stuff will be removed in favor of standard AWS CredentialsProvider. So, there will be a lot of breaking changes for the SI-AWS 1.0.0.
I am trying to write some unit tests for some code that uses Jersey to hit a RESTful web service, and am using Mockito to mock out some things. Here's my code:
#Test
void test() {
given:
// WebResource is a Jersey/JAX-RS construct.
WebResource mockResource = Mockito.mock(WebResource)
// Address.groovy is a POJO from my project.
Address mockAddress = Mockito.mock(Address)
// THE NEXT LINE IS WHAT IS THROWING THE EXCEPTION:
Mockito.when(mockResource.get(Mockito.any())).thenReturn(mockAddress)
when:
<omitted for brevity>
then:
<omitted for brevity>
}
As you can see, I'm trying to coerce Jersey to return my mockAddress instance whenever the WebResource attempts to do an HTTP GET.
When this runs I get:
groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method com.sun.jersey.api.client.WebResource$$EnhancerByMockitoWithCGLIB$$1c2e51fa#get.
Cannot resolve which method to invoke for [null] due to overlapping prototypes between:
[class com.sun.jersey.api.client.GenericType]
[class java.lang.Class]
at groovy.lang.MetaClassImpl.chooseMostSpecificParams(MetaClassImpl.java:3031)
at groovy.lang.MetaClassImpl.chooseMethodInternal(MetaClassImpl.java:2983)
at groovy.lang.MetaClassImpl.chooseMethod(MetaClassImpl.java:2926)
at groovy.lang.MetaClassImpl.getMethodWithCachingInternal(MetaClassImpl.java:1203)
at groovy.lang.MetaClassImpl.createPojoCallSite(MetaClassImpl.java:3130)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.createPojoSite(CallSiteArray.java:129)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallSite(CallSiteArray.java:163)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at com.me.myapp.MyUnitTest.test(MyUnitTest.groovy:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
<large stack trace omitted for brevity>
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Where MyUnitTest.groovy:19 is the line:
Mockito.when(mockResource.get(Mockito.any())).thenReturn(mockAddress)
Any ideas as to what is going on?
WebResource's get() method is overloaded with get(Class) and get(GenericType).
That seems to be where is ambiguity is, as described in the message. That being said, it doesn't really seems appropriate to use Mockito.any(). I'm not a big Mockito user, so I don't know of the normal use cases for using it. When I try to use it with Java, I'll get a compile error, as Mockit.any() will return Object, and neither of the overloaded methods accept Object as an argument.
That being said, the behavior you are mocking, is that when you call get on the WebResource it should return an Address object, so you'll would want to pass Address.class (or Address in the case of Groovy might be OK, as you mentioned in your previous post) to the get method.
Something that should work (at least when I tested with Java) is something like:
WebResource resource = Mockito.mock(WebResource.class);
Address address = Mockito.mock(Address.class);
Mockito.when(resource.get(Address.class)).thenReturn(address);
Mockito.when(address.toString()).thenReturn("Hello World");
Address a = resource.get(Address.class);
System.out.println(a);
This should print out "Hello World"
This is due to the multiple dispatch mechanism in Groovy.
Just cast the result of the any() call to the type of the overloaded method's parameter you are stubbing.
when(mockResource.get(any() as Address)).thenReturn(mockAddress)
// this also works
when(mockResource.get(any(Address) as Address)).thenReturn(mockAddress)
Imports:
import static org.mockito.ArgumentMatchers.any
import static org.mockito.Mockito.when
More details on this answer, this and this blog posts.