0
votes

I have a scala project that uses a java library (cipango). I'm trying to mock one of the methods in the library which returns a java.util.Iterator. On the scala side, I have a scala.collections.Iterator[_] which I'm converting using scala.collections.JavaConversions. But it won't compile, and fails with the message:

Error:(63, 60) type mismatch;
found   : java.util.Iterator[_$1] where type _$1
required: java.util.Iterator[?0] where type ?0
   mockSipApplicationSessions(id).getSessions.andReturn(sessionsAsJavaIterator)

(One detail that is probably not relevant, but I'll mention, is that the actual elements in sessionsAsJavaIterator are themselves mocks of a java interface.)

I have created a small example that shows a similar problem. The error message for the example is not exactly the same but it's quite similar.

Java:

import java.util.Iterator;

public interface IterateMe {
    Iterator<?> getSomething();
}

public class SomeClass {
}

Scala:

import org.scalatest.mock.EasyMockSugar
import org.scalatest.{Matchers, FunSpecLike}
import scala.collection.JavaConversions._

class AdhocSpec extends FunSpecLike  with Matchers with EasyMockSugar {
  describe("IterateMe") {
    it("can not be mocked!") {
      val m = mock[IterateMe]
      val toReturn: java.util.Iterator[_] = Iterator(mock[SomeClass])

      expecting { m.getSomething().andReturn(toReturn) }

      whenExecuting(m) {
        m.getSomething.next() should equal("A")
      }
    }
  }
}

Compilation error:

Error:(13, 46) type mismatch;
 found   : java.util.Iterator[(some other)_$1(in value <local AdhocSpec>)] where type (some other)_$1(in value <local AdhocSpec>)
 required: java.util.Iterator[_$1(in value <local AdhocSpec>)] where type _$1(in value <local AdhocSpec>)
      expecting { m.getSomething().andReturn(toReturn) }
1

1 Answers

2
votes

Try this. At some point you need to deal with an actual parameterized type in the test. I also fixed the test to what I think you wanted since "A" isn't really mentioned anywhere in your code.

import org.scalatest.mock.EasyMockSugar
import org.scalatest.{Matchers, FunSpecLike}
import scala.collection.JavaConversions._

class AdhocSpec extends FunSpecLike with Matchers with EasyMockSugar {
  describe("IterateMe") {
    it("can be mocked!") {
      val m = mock[IterateMe]
      val someObject: SomeClass = mock[SomeClass]
      val toReturn: java.util.Iterator[SomeClass] = Iterator[SomeClass](someObject)

      expecting {m.getSomething.asInstanceOf[java.util.Iterator[SomeClass]].andReturn(toReturn) }

      whenExecuting(m) {
        m.getSomething.next() should equal(someObject)
      }
    }
  }
}