Mockito Stubbing连续调用(迭代器式存根),异常并返回void

时间:2015-11-04 21:39:04

标签: scala mockito scalatest

我努力让以下测试工作,基本上我希望模拟的服务调用在第一次调用时抛出异常,并在第二次调用时正常工作。服务方法不返回任何内容(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$2$$anonfun$apply$mcV$sp$1.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

1 个答案:

答案 0 :(得分:1)

原来我正在设置模拟错误,解决方案如下..

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

而不是错误的

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