Question

I'm using ScalaTest 2.0 and ScalaMock 3.0.1. How do I assert that a method of a mocked trait is called never?

import org.scalatest._
import org.scalamock._
import org.scalamock.scalatest.MockFactory

class TestSpec extends FlatSpec with MockFactory with Matchers {

  "..." should "do nothing if getting empty array" in {
    val buyStrategy = mock[buystrategy.BuyStrategyTrait]
    buyStrategy expects 'buy never
    // ...
  }
}
Was it helpful?

Solution

There are two styles for using ScalaMock; I will show you a solution showing the Mockito based style of Record-Then-Verify. Let's say you had a trait Foo as follows:

trait Foo{
  def bar(s:String):String
}

And then a class that uses an instance of that trait:

class FooController(foo:Foo){  
  def doFoo(s:String, b:Boolean) = {
    if (b) foo.bar(s)
  }
}

If I wanted to verify that given a false value for the param b, foo.bar is not called, I could set that up like so:

val foo = stub[Foo]
val controller = new FooController(foo)
controller.doFoo("hello", false)
(foo.bar _).verify(*).never 

Using the *, I am saying that bar is not called for any possible String input. You could however get more specific by using the exact input you specified like so:

(foo.bar _).verify("hello").never 

OTHER TIPS

If you use expectations-first style, this is actually the default for any methods that you don't explicitly set expectations for. So you don't need to do anything. However, as a general point, you must not reuse mocks between tests that have different expectations - that won't work - rather, you must create a new mock for each test.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top