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
// ...
}
}
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.
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]
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With