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

ぐ巨炮叔叔 提交于 2019-12-23 12:26:55

问题


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



来源:https://stackoverflow.com/questions/29841267/scalamock-how-to-get-expects-for-proxy-mocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!