Mocking a val of a trait with scala-mock

9.2k views Asked by At

I'd like to mock a val of a trait. for example, in this code, to mock the val baz:

trait Foo {
  def bar(): Int
  val baz: Int
}

val fooMock = mock[Foo]
(fooMock.bar _).expects().returning(5)
(fooMock.baz _).expects().returning(6) //doesn't compile

doSomeThing(fooMock)

To solve this in my test, I've extended Foo, and implemented baz in the following manner:

trait FooTest extends Foo {
  override val baz: Int = 5
}

val fooMock = mock[FooTest]
(fooMock.bar _).expects().returning(6)

doSomeThing(fooMock)

But this is ugly, and I was hoping that there is a more standard way of doing this with scala mock.

I've seen the answer to this question, but it requires changing the val to def in the trait, and I'd like to keep baz a val

1

There are 1 answers

3
Paul Butcher On BEST ANSWER

This isn't supported by ScalaMock's macro-based mocks as things currently stand. It is one of the things that we hope to address when scala.meta becomes available.

If you want to track this, you might want to follow:

https://github.com/paulbutcher/ScalaMock/issues/40

There is another option that might be of interest - ScalaMocks's proxy-based mocks do support mocking vals. For an example, see the ScalaMock test suite:

https://github.com/paulbutcher/ScalaMock/blob/master/core_tests/src/test/scala/com/paulbutcher/test/proxy/ProxyMockTest.scala#L163