0

I'm struggling to get the following test working, basically I want the mocked service call to throw an exception when first called, and work ok on the 2nd invocation. The service method returns nothing (void/Unit), written in 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")
  }
}

Here is the build.sbt file

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

Tony Murphy
  • 711
  • 9
  • 22

1 Answers1

1

Turns out the I was setting up the mock incorrectly, solution below..

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

instead of the incorrect

  Mockito.doThrow(new RuntimeException).when(myService.sideEffect())
  Mockito.doNothing().when(myService.sideEffect())
Tony Murphy
  • 711
  • 9
  • 22