小编Phi*_*ipp的帖子

无法在 Scala 中使用 Mockito ArgumentMatchers

我正在使用 ScalaMock 和 Mockito

我有这个简单的代码

class MyLibrary {
   def doFoo(id: Long, request: Request) = {
      println("came inside real implementation")
      Response(id, request.name)
   }
}

case class Request(name: String)
case class Response(id: Long, name: String)
Run Code Online (Sandbox Code Playgroud)

我可以使用此代码轻松模拟它

val lib = new MyLibrary()
val mock = spy(lib)
when(mock.doFoo(1, Request("bar"))).thenReturn(Response(10, "mock"))
val response = mock.doFoo(1, Request("bar"))
response.name should equal("mock")
Run Code Online (Sandbox Code Playgroud)

但是如果我将代码更改为

val lib = new MyLibrary()
val mock = spy(lib)
when(mock.doFoo(anyLong(), any[Request])).thenReturn(Response(10, "mock"))
val response = mock.doFoo(1, Request("bar"))
response.name should equal("mock")
Run Code Online (Sandbox Code Playgroud)

我看到它进入真正的实现并得到一个空指针异常。

scala mockito

2
推荐指数
1
解决办法
1067
查看次数

ScalaTest,Mockito,Guice和PartialMocking

我正在使用Google Guice作为DI框架,我正在为使用Google Guice的课程编写单元测试.我也试图做部分嘲笑.

这是我写的代码

class Test1 {
   def test1() = "I do test1"
}
class Test2 {
   def test2() = "I do test2"
}
class TestPartialMock @Inject()(t1: Test1, t2: Test2) {
   def test3() = "I do test3"
   def createList() : List[String] = List(t1.test1(), t2.test2(), test3())
}
Run Code Online (Sandbox Code Playgroud)

我的目标是为上面的代码编写测试用例,但我只想模拟 test3

我写了这个测试用例

class TestModule extends AbstractModule with ScalaModule with MockitoSugar {
   override def configure() = {
      bind[Test1]
      bind[Test2]
      val x = mock[TestPartialMock]
      when(x.test3()).thenReturn("I am mocked")
      when(x.createList()).thenCallRealMethod()
      bind(classOf[TestPartialMock]).toInstance(x)
   }
}

class PartialMockTest extends FunSpec …
Run Code Online (Sandbox Code Playgroud)

unit-testing scala guice mockito scalatest

0
推荐指数
1
解决办法
861
查看次数

标签 统计

mockito ×2

scala ×2

guice ×1

scalatest ×1

unit-testing ×1