Scalamock: How to get “expects” for Proxy mocks?

2019-06-23 19:46发布

问题:

I am using Scalamock with ScalaTest, and am trying to mock a Java interface. I currently have:

private val _iface = mock [MyInterface]

now I want to do

_iface expects `someMethod returning "foo" once

But the compiler does not find expects.

I imported org.scalatest._ and org.scalamock.scalatest._. What else am I missing?

回答1:

First of all, proxy mocks are not supported very well in ScalaMock 3, and I think they will be completely removed in ScalaMock 4. Do you really need to use proxy mocks instead macro mocks?

This should work:

package example

import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.scalamock.scalatest.proxy.MockFactory

trait MyInterface {
    def someMethod : String
}

class MyTest extends FlatSpec with Matchers with MockFactory {
  "MyInterface" should "work" in {
    val m = mock[MyInterface]
    m.expects('someMethod)().returning("foo")
    m.someMethod shouldBe "foo"
  }
}

If not, please check ScalaMock proxy mocks unit tests for more examples.



回答2:

I think it should be something more like:

import org.scalamock.scalatest.MockFactory

class MyTest extends FlatSpec with Matchers with MockFactory {
  "MyInterface" should "work" in {
    val m = mock[MyInterface]
    (m.someMethod _).expects().returning("foo")
    m.someMethod shouldBe "foo"
  }
}

I think the expects arg is expecting the arg to the function



回答3:

I use scalaMock version 4.1.0, this works for me:

For some trait:

trait MyInterface { def someMethod(n1: Int, n2: Int) }

This should be put into a test

val myInterfaceMock = mock[MyInterface]

myInterfaceMock.someMethod _ expects (1,2)

For more reading: scalaMock Guide, you'll find some examples there