Search code examples
unit-testingscalamockingscalatest

How to assert that mocked method is never called using ScalaTest and ScalaMock?


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
    // ...
  }
}

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