Using Mockito & Guice to test interfaces with generics in Scala

我是研究僧i 提交于 2020-01-05 05:57:16

问题


I am new to Scala, and I'm running into this problem when I'm trying to unit test some of my interfaces.

I have an InputService trait with method

def poll(parameters: HashMap[String, String]): Option[T]

where T is generic, so InputService has a type parameter [T].

In my module, I have

val inputService: InputService[String] = mock(classOf[InputService[String]])
bind[InputService[String]].toInstance(inputService)

and in my InputServiceTest, I have

  var inputService: InputService[String] = _
  before {
    inputService = Guice.createInjector(new MockWatcherModule).getInstance(classOf[InputService[String]])
  }

But the issue is when I run it, it gives me this error

Exception encountered when invoking run on a nested suite - Guice configuration errors:
1) No implementation for services.InputService was bound.
  while locating services.InputService

I think it's because it's looking for services.InputService to bound, but it only has services.InputService[String]. However, when I just use InputService instead of InputService[String], I get the error Trait missing Type Parameter.

Any suggestions?

EDIT: Turns out that I can use typeLiteral from scala-guice and KeyExtensions to solve my issue. Thanks Tavian!


回答1:


Due to type erasure, in the getInstance(classOf[InputService[String]]) call, you're just passing InputService.class. You need to pass a TypeLiteral instead to encode the generic type information. From a quick Google it looks like

import net.codingwell.scalaguice._
import net.codingwell.scalaguice.InjectorExtensions._

Guice.createInjector(new MockWatcherModule).instance[InputService[String]]

will work.



来源:https://stackoverflow.com/questions/31681976/using-mockito-guice-to-test-interfaces-with-generics-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!