使用Mockito& amp;在Scala中使用泛型测试接口的向导 [英] Using Mockito & Guice to test interfaces with generics in Scala

查看:50
本文介绍了使用Mockito& amp;在Scala中使用泛型测试接口的向导的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Scala的新手,在尝试对某些接口进行单元测试时,我就遇到了这个问题.

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

我具有方法的InputService特征

I have an InputService trait with method

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

其中T是通用的,因此InputService具有类型参数[T].

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

在我的模块中,我有

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

在我的InputServiceTest中,我有

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

我认为这是因为它正在寻找绑定的services.InputService,但是它仅具有services.InputService [String].但是,当我只使用InputService而不是InputService [String]时,出现错误 Trait缺少类型参数.

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.

有什么建议吗?

事实证明,我可以使用scala-guice和KeyExtensions中的typeLiteral解决我的问题.谢谢塔维安!

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

推荐答案

由于要进行擦除,因此在 getInstance(classOf [InputService [String]])调用中,您只是传递了 InputService.class .您需要传递 TypeLiteral 来编码通用类型信息.从一个快速的Google看来,

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]]

将起作用.

这篇关于使用Mockito& amp;在Scala中使用泛型测试接口的向导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆