Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    // ...
  }
}
like image 580
moteutsch Avatar asked Jan 07 '14 12:01

moteutsch


People also ask

What is ScalaMock?

ScalaMock is a native, open-source Scala mocking framework written by Paul Butcher that allows you to mock objects and functions. ScalaMock supports three different mocking styles: Function mocks. Proxy (dynamic) mocks. Generated (type-safe) mocks.

What is MockitoSugar?

MockitoSugar trait provides some basic syntax sugar for Mockito. Using the Mockito API directly, you create a mock with: val mockCollaborator = mock(classOf[Collaborator]) Using this trait, you can shorten that to: val mockCollaborator = mock[Collaborator]

What is stub in Scala?

A stub object that supports the record-then-verify style is created with stub . For example: val heaterStub = stub[Heater] Return values that are used by the system under test can be set up by using when before running the tested system.

What is default assertion in Scala?

You can use: assert for general assertions; assertResult to differentiate expected from actual values; assertThrows to ensure a bit of code throws an expected exception.


1 Answers

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 
like image 192
cmbaxter Avatar answered Sep 30 '22 17:09

cmbaxter