简体   繁体   中英

Calling an overloaded java generic method from scala

I'm using Mockito to mock an object with a method which returns an un-parametrized ArrayList, and I cannot figure out how to get this to work

Method signature to mock

public java.util.ArrayList getX()

Test code

var mockee = mock(classOf[Mockee])
when(mockee.getX).thenReturn(Lists.newArrayList(x): ArrayList[_])

This actually compiles fine in IntelliJ, but at runtime throws:

[error] ....scala:89: overloaded method value thenReturn with alternatives:
[error]   (java.util.ArrayList[?0],<repeated...>[java.util.ArrayList[?0]])org.mockito.stubbing.OngoingStubbing[java.util.ArrayList[?0]] <and>
[error]   (java.util.ArrayList[?0])org.mockito.stubbing.OngoingStubbing[java.util.ArrayList[?0]]
[error]  cannot be applied to (java.util.ArrayList[_$1])
[error]       when(mockee.getX).thenReturn(Lists.newArrayList(x): ArrayList[_])

The following works for me:

val mockee = mock(classOf[Mockee])
when[ArrayList[_]](mockee.getX).thenReturn(Lists.newArrayList)

assuming the "Lists" class is from the Google collections (now Guava).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM