4

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

Community
  • 1
  • 1
lev
  • 3,986
  • 4
  • 33
  • 46

1 Answers1

5

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

Paul Butcher
  • 10,722
  • 3
  • 40
  • 44
  • I wasn't aware of the proxy mocks. The test file gives some good examples, but is there any documentations about it? – lev Nov 28 '14 at 04:51
  • 1
    Apologies, but the documentation for proxy mocks is (as you've seen) thin on the ground. The good thing is that they're much simpler than macro-based mocks, so pretty much the examples in the test file are "it" :-) – Paul Butcher Nov 28 '14 at 15:52
  • Is it still not supported in the newer versions? – ClassNotFoundException Nov 01 '19 at 15:48