8

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[_])
Jon Freedman
  • 9,469
  • 4
  • 39
  • 58
  • I may be wrong, but I thought `ArrayList[_]` in Scala is not the same as an unparameterized ArrayList, it is an existential type -- ie it has a type parameter, but it's bound at a funny place. I think the unparameterized type would be `ArrayList[AnyRef]` ie parameterized by `java.lang.Object`. – Owen Sep 09 '11 at 17:33
  • 1
    This looks like a compile-time error, not a run-time error. Scala's existential type `ArrayList[_]` is its closest approximation to Java's wildcard type `ArrayList>`. You actually have a *raw type*, `ArrayList`. Two SO questions to look into: [Scala's existential types](http://stackoverflow.com/questions/1031042/scalas-existential-types) and [Raw types and wildcard...](http://stackoverflow.com/questions/3489947/raw-types-unbounded-wilcard-and-bounded-wildcard) – Kipton Barros Sep 09 '11 at 19:48
  • You're right it is a compile time error, but not highlighted by the scala plugin. I can work around this by using `thenAnswer(new Answer[ArrayList[_]]{ def answer(arg: InvocationOnMock) = Lists.newArrayList(x)})` but that's not very nice – Jon Freedman Sep 26 '11 at 17:26

1 Answers1

8

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).