0

I get the error "verify should appear after all code under test has been exercised" with the following:

class CowTest extends MockFactory {

  Cow.init(testCowProcesses)

  @Test
  def noProcessesTest: Unit = {
    val cow: Cow = Cow(testCowProcesses)
    cow.simulateOneDay(0 nanoseconds)
  }


  @Test
  def processSimulationTest: Unit = {
    val NUMBER_OF_TRIES: Int = 10
    val cow: Cow = Cow(testCowProcesses)
    for (ii <- 0 until NUMBER_OF_TRIES) {
      cow.simulateOneDay(0 nanoseconds)
    }
    (cow.metabolicProcess.simulateOneDay _).verify(0 nanoseconds).repeated(NUMBER_OF_TRIES)
  }
}

testCowProcesses is defined in another file, like this (abbreviated):

object CowTesters extends MockFactory {
  val metProc = stub[MetabolicProcess]
  (metProc.replicate _).when().returns(metProc)

  val testCowProcesses = CowProcesses(metProc)

}

I don't quite understand the error message. If I comment out the verify line, the test runs. Alternatively, if I comment out the first test, the second test can run. There are no other tests in the test class. This seems to indicate that the stub objects cannot be reused, as they were in mockito (I'm adapting code from mockito).

Is the best solution to reinstantiate the mock objects, perhaps by converting CowTesters into a class?

Edit:

I confirmed the above suggestion works (not sure if it is the best), but in the mean time I did something a bit more convoluted to get me through compiles:

//TODO: once all tests are converted to ScalaMock, 
//TODO: just make this a class with a companion object
trait CowTesters extends MockFactory {
  val metProc = stub[MetabolicProcess]
  (metProc.replicate _).when().returns(metProc)

  val testCowProcesses = CowProcesses(metProc)
}
object CowTesters extends CowTesters {
  def apply(): CowTesters = new CowTesters {}
}
bbarker
  • 11,636
  • 9
  • 38
  • 62

1 Answers1

1

From your code above, it seems you are either trying to use JUnit or TestNG. ScalaMock doesn't support either of those frameworks directly, which is why you are struggling with the verification of mocks. You need to implement your tests using either ScalaTest, or Specs2. See http://scalamock.org/user-guide/integration/

The conversion from JUnit to ScalaTest should be pretty straightforward if you switch to e.g. a FunSuite: http://www.scalatest.org/user_guide/selecting_a_style

Philipp
  • 967
  • 6
  • 16
  • I'm amazed it worked as well as it did then. I think that was the only problem I had in converting at least 30 test classes using mockito. So with ScalaTest, it will reset state for each test function? – bbarker Oct 28 '17 at 09:56
  • 1
    No it won't by default, but you can use a Fixture or the `OneInstancePerTest` mixins: http://scalamock.org/user-guide/sharing-scalatest/ – Philipp Oct 28 '17 at 09:58