Mockito Stubbing 连续调用(迭代器式存根)、异常和 return void

Mockito Stubbing consecutive calls (iterator-style stubbing), exceptions and return void

我正在努力让以下测试正常工作,基本上我希望模拟服务调用在第一次调用时抛出异常,并在第二次调用时正常工作。服务方法returns没什么(void/Unit),用scala写的

import org.mockito.{Mockito}
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfter, FeatureSpec}
import org.mockito.Mockito._

class MyMocksSpec extends FeatureSpec with BeforeAndAfter with MockitoSugar {

  var myService: MyService = _

  var myController: MyController = _

  before {
    myService = mock[MyService]
    myController = new MyController(myService)
  }

  feature("a feature") {
    scenario("a scenario") {
      Mockito.doThrow(new RuntimeException).when(myService.sideEffect())
      Mockito.doNothing().when(myService.sideEffect())
      myController.showWebPage()
      myController.showWebPage()
      verify(myService, atLeastOnce()).sayHello("tony")
     verify(myService, atLeastOnce()).sideEffect()

    }
  }
}

class MyService {
  def sayHello(name: String) = {
    "hello " + name
  }

  def sideEffect(): Unit = {
    println("well i'm not doing much")
  }
}

class MyController(myService: MyService) {

  def showWebPage(): Unit = {
    myService.sideEffect()
    myService.sayHello("tony")
  }
}

这是 build.sbt 文件

name := """camel-scala"""

version := "1.0"

scalaVersion := "2.11.7"

libraryDependencies ++= {
 val scalaTestVersion = "2.2.4"
 Seq(
   "org.scalatest" %% "scalatest" % scalaTestVersion % "test",
   "org.mockito" % "mockito-all" % "1.10.19")
}


Unfinished stubbing detected here:
-> at     MyMocksSpec$$anonfun$$anonfun$apply$mcV$sp.apply$mcV$sp(MyMocksSpec.scala:24)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, you naughty developer!
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

I followed the example (I think) here

原来我设置的 mock 不正确,解决方法如下..

  Mockito.doThrow(new RuntimeException).when(myService).sideEffect()
  Mockito.doNothing().when(myService).sideEffect()

而不是不正确的

  Mockito.doThrow(new RuntimeException).when(myService.sideEffect())
  Mockito.doNothing().when(myService.sideEffect())