我有一个使用java库(cipango)的scala项目。我试图模拟库中返回java.util.Iterator的方法之一。在scala方面,我有一个scala.collections.Iterator [_],我使用scala.collections.JavaConversions进行转换。但它不会编译,并且失败并显示消息:
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)
(可能不相关的一个细节,但我要提到的是,sessionsAsJavaIterator中的实际元素本身就是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")
}
}
}
}
编译错误:
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) }
答案 0 :(得分:2)
试试这个。在某些时候,您需要在测试中处理实际的参数化类型。我还将测试修改为我认为你想要的,因为&#34; A&#34;在代码中的任何地方都没有提到过。
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)
}
}
}
}