如何用ScalaMock模拟Guice模块中的接口?

时间:2016-09-18 07:54:28

标签: scala mocking guice

如何使用ScalaMock简单地模拟Guice中注入所需的接口?

2 个答案:

答案 0 :(得分:0)

通过将模拟实例绑定到类名称并使用该模块为测试注入对象来使用单独的测试模块。

测试模块是这样的:

class TestModule extends AbstractModule {
  override def configure(): Unit = {
    val mockObject = mock[ClassName]
    bind(classOf[ClassName]).toInstance(mockObject)
  }
}

规范是这样的:

class SomeSpec extends FlatSpec {
  val injector = Guice.createInjector(new TestModule)
  val mockObject = injector.getInstance(classOf[ClassName])
} 

答案 1 :(得分:0)

我最终使用了

import org.scalamock.MockFactoryBase
import org.scalatest.exceptions.TestFailedException

trait MyMockFactory extends MockFactoryBase {
  type ExpectationException = TestFailedException

  override protected def newExpectationException(message: String, methodName: Option[Symbol]): TestFailedException = ???
}

并在TestModule中

class TestModule extends AbstractModule with MyMockFactory {
  override def configure(): Unit = {
    val mockObject = mock[ClassName]
    bind(classOf[ClassName]).toInstance(mockObject)
  }
}