mockito scala中的模拟case类

0pizxfdo  于 2022-11-08  发布在  Scala
关注(0)|答案(1)|浏览(143)

我有个特点

trait Writer[T <: Attribute] {
  def read(boundingBox: BoundingBox): Future[List[T]]
}

和一个case类

case class WriterImpl[T <: Attribute]()(implicit manifest: Manifest[T]) extends Writer[T] with LazyLogging {

override def read(boundingBox: BoundingBox): Future[List[T]] = {
}
..
}

在Test类中,我想模拟方法read()
我用精确值试过了

val writer = mock[WriterImpl[Attrib]]
        when(writer.read(new BoundingBox(41.90178412, 41.8798685, -87.62687021, -87.64884287)))
          .thenReturn(Future.successful(scala.collection.immutable.List(list)))

 verify(writer).read(new BoundingBox(41.90178412, 41.8798685, -87.62687021, -87.64884287))

也尝试了

val writer = mock[WriterImpl[Attrib]]
            when(writer.read(ArgumentMatchers.any()))
              .thenReturn(Future.successful(scala.collection.immutable.List(list)))

     verify(writer).read(ArgumentMatchers.any())

它调用的不是mock方法,而是实际方法

ygya80vv

ygya80vv1#

在第一个范例中,问题是您使用两个不同的BoundingBox对象做为read方法的参数:一个用于when,另一个用于verify。它们不会匹配,因为在运行时它们是同一个BoundingBox类的不同示例。您应该使用同一个对象。将它存储在when子句之前,然后调用verify并传递同一个对象。
我假设您刚刚删除了whenverify子句之间任何地方对writer.read(...)的明显调用。verify至少需要一个对read的调用,否则将抛出"Wanted but not invoked: writerImpl.read(...); Actually, there were zero interactions with this mock.."
第二个示例应该可以运行,但是如果您尝试检查结果,仍然会遇到相同的问题。一个在when中,另一个在verify中。由于它们在运行时是两个不同的对象,因此它们将不匹配:

result shouldBe Future.successful(scala.collection.immutable.List(new Attribute))

该输出确认运行时看到2个不同的示例:

Expected :Future(Success(List(org.scala.snippets.Test$Attribute@373052b5)))
Actual   :Future(Success(List(org.scala.snippets.Test$Attribute@17207f5b)))

同样,只需将Future存储在when之前,并将相同的Future传递给whenshouldBe。通过这些调整,这应该可以工作。检查read的结果,确认从调用中返回了相同的Future

import Test.{Attribute, BoundingBox, WriterImpl}

import org.mockito.MockitoSugar
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

import scala.concurrent.Future

class ProgramTest extends AnyWordSpec with MockitoSugar with Matchers {
  "Program " should {
    "return the mocked succf " in {
      val succf  = Future.successful(scala.collection.immutable.List(new Attribute))
      val bb     = new BoundingBox(41.90178412, 41.8798685, -87.62687021, -87.64884287)
      val writer = mock[WriterImpl[Attribute]]
      when(writer.read(bb)).thenReturn(succf)

      val result = writer.read(bb)

      verify(writer, times(1)).read(bb)
      result shouldBe succf
    }
  }
}

这是我的build.sbt,如果您需要的话:

libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.12" % Test
libraryDependencies += "org.scalatestplus" %% "scalacheck-1-16" % "3.2.12.0" % Test
libraryDependencies += "org.scalatestplus" %% "mockito-4-5" % "3.2.12.0" % Test
libraryDependencies += "org.mockito" % "mockito-core" % "4.6.1" % Test
libraryDependencies += "org.mockito" %% "mockito-scala" % "1.17.7" % Test

相关问题