1

Recently I started usage of ScalaMock library in my unit tests and it works fine, until I want to use the same stab (declared globally in a test suite) in more than one test.

Here is an example:

import org.scalamock.scalatest.MockFactory
import org.scalatest.FunSuite

trait Bank {
  def transaction(amount: Double): Double
  def deposit(amount: Double): Double
}

class OloloSuite extends FunSuite with MockFactory {
  val fakeBank = stub[Bank]
  (fakeBank.transaction _).when(10.0).returns(9.0)
  (fakeBank.deposit _).when(10.0).returns(11.0)

  //Pass
  test("Transaction test") {
    assert(fakeBank.transaction(10.0) === 9.0)
  }

  //Fails
  test("Deposit test") {
    assert(fakeBank.deposit(10.0) === 11.0)
  }
}

How to make "Deposit test" pass?

Alex Fruzenshtein
  • 2,846
  • 6
  • 32
  • 53

2 Answers2

3

please read the docs here: http://scalamock.org/user-guide/sharing-scalatest/

Your options:

  • mix in OneInstancePerTest with your test suite

  • or create a fixture (see link above for example)

Philipp
  • 967
  • 6
  • 16
1

A quick fix for this is to move "expectation" functions inside of the tests:

val fakeBank = stub[Bank]

test("Transaction test") {
  (fakeBank.transaction _).when(10.0).returns(9.0).anyNumberOfTimes()
  assert(fakeBank.transaction(10.0) === 9.0)
}

test("Deposit test") {
  (fakeBank.deposit _).when(10.0).returns(11.0).anyNumberOfTimes()
  assert(fakeBank.deposit(10.0) === 11.0)
}

But it's still not convenient if you want to have the same result for different tests :(

Alex Fruzenshtein
  • 2,846
  • 6
  • 32
  • 53