Scala测试与Mockito的特征

时间:2014-07-03 14:54:11

标签: scala mockito

我是Scala中的新人。目前我正在追踪对特征进行模拟测试。有人可以帮我实施吗?我想在特性SeasonalityServiceImpl和测试方法hMock.doSomeForF()中模拟方法seasonalityDao.doSomeForB和seasonalityDao.doSomeForB1。

更新: 我根据下面的评论更正了代码。在这种情况下,当我尝试非常模拟方法验证(sMock).doSomeForB()验证(sMock).doSomeForB1()时,我收到下一个错误: 想要但未被引用: seasonalityDao.doSomeForB(); - >在Main $$ anonfun $ 1.apply $ mcV $ sp(Main.scala:12) 实际上,这个模拟没有互动。

这是一个代码(我刚刚简化了项目的重要部分):

import org.scalatest._
import org.mockito.Mockito._

class Main extends FunSuite with SeasonalityServiceComponentImpl with SeasonalityDaoComponent {
  test("some test") {
    def hMock = mock(classOf[SeasonalityServiceImpl])
    def sMock = mock(classOf[SeasonalityDao])

    when(sMock.doSomeForB()).thenReturn(Option(2))
    when(sMock.doSomeForB1()).thenReturn(10)

    verify(sMock).doSomeForB()
    verify(sMock).doSomeForB1()

    println("With Option " + hMock.doSomeForF())
    println("Without Option " + hMock.doSomeForF1())
  }

  override def seasonalityDao: SeasonalityDao = mock(classOf[SeasonalityDao])

  override def seasonalityService: SeasonalityService = mock(classOf[SeasonalityService])
}

trait SeasonalityDaoComponent {
  def seasonalityDao: SeasonalityDao

  trait SeasonalityDao {
    def doSomeForB(): Option[Int]
    def doSomeForB1(): Int
  }
}

trait SeasonalityServiceComponent {
  def seasonalityService: SeasonalityService

  trait SeasonalityService {
    def doSomeForF(): Option[Int]
    def doSomeForF1(): Int
  }
}

trait SeasonalityServiceComponentImpl extends SeasonalityServiceComponent {
  this: SeasonalityDaoComponent =>

  trait SeasonalityServiceImpl extends SeasonalityService {
    def doSomeForF(): Option[Int] = {
      seasonalityDao.doSomeForB()
    }
    def doSomeForF1(): Int = {
      seasonalityDao.doSomeForB1()
    }
  }
}

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您希望对doSomeForBdoSomeForB1的模拟进行调用。但是,您的代码在之前验证了这个期望,因此测试失败。

此外,您的模拟被定义为本地方法,这意味着在每次调用时都会获得 new 模拟对象。您需要将它们转换为本地val,以便您交互(并验证)同一个实例。

将其修改为:

  test("some test") {
   // this seems unused -->>  def hMock = mock(classOf[SeasonalityServiceImpl])
    val sMock = mock(classOf[SeasonalityDao]) // you need it to be a val, not a def

    when(sMock.doSomeForB()).thenReturn(Option(2))
    when(sMock.doSomeForB1()).thenReturn(10)

    println("With Option " + sMock.doSomeForF()) // note that you should call them on sMock
    println("Without Option " + sMock.doSomeForF1())

    verify(sMock).doSomeForB()
    verify(sMock).doSomeForB1()
  }